There is an algorithm itself, but the question is this: when the first half of the array is sorted (the left side, the one that is smaller than the pivot), it is supposed to leave the method because both conditions do not work
if (left < j) qs(items, left, j); if (i < right) qs(items, i, right); but he jumps back into the second if and somehow gives the value i = 3 and starts sorting the second half. The question is how did he understand it? Or is it a recursive call feature?
Here is the code itself :
class Quicksort {
// Организовать вызов фактического метода быстрой сортировки static void qsort(int[] items) { qs(items, 0, items.length - 1); } // Рекурсивная версия метода быстрой сортировки символов private static void qs(int[] items, int left, int right) { int i = left; int j = right; int pivot, TEMP; pivot = items[(left + right) / 2]; do { while ((items[i] < pivot) && (i < right)) i++; while ((pivot < items[j] && (j > left))) j--; if (i <= j) { TEMP = items[i]; items[i] = items[j]; items[j] = TEMP; i++; j--; } } while (i <= j); if (left < j) qs(items, left, j); if (i < right) qs(items, i, right); } }
public class QSDemo {
public static void main(String[] args) { int[] a = {17, -24, 20, -15, -21, -3, 13}; System.out.println("Исходный массив: "); for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); // Отсоритровать массив Quicksort.qsort(a); System.out.println("Отсортированный массив: "); for (int i = 0; i < a.length; i++) System.out.print(a[i] + " "); } }