1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
public class QuickSort { public static void quickSort(int[] arr) { if (arr == null || arr.length < 2) { return; } quickSort(arr, 0, arr.length - 1); } public static void quickSort(int[] arr, int L, int R) { if (L < R) { swap(arr, R, L + (int)(Math.random() * (R - L + 1))); int[] p = partition(arr, L, R); quickSort(arr, L, p[0] - 1); quickSort(arr, p[1] + 1, R); } } public static int[] partition(int[] arr, int L, int R) { int less = L - 1; int more = R; int pivot = arr[R]; while (L < more) { if (arr[L] < pivot) { swap(arr, ++less, L++); } else if (arr[L] > pivot) { swap(arr, --more, L); } else { L++; } } swap(arr, more, R); return new int[]{less + 1, more}; } public static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } }
|