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 49 50 51 52
| public static void quickSort(Comparable[] array) { quickSort(array, 0, array.length-1); }
private static void quickSort(Comparable[] array, int low, int high) { if (low >= high) { return; }
if (high - low + 1 < 16) { insertSort(array, low, high); return; }
swap(array, low, low+(int)(Math.random()*(high-low+1))); Comparable key = array[low]; int lt = low; int gt = high + 1; int index = low + 1; while (index < gt) { if (array[index].compareTo(key) < 0) { lt++; swap(array, index, lt); index++; } else if (array[index].compareTo(key) > 0) { gt--; swap(array, index, gt); } else { index++; } } swap(array, low, lt);
quickSort(array, low, lt-1); quickSort(array, gt, high); }
public static void insertSort(Comparable[] array, int low, int high) { for (int i = low+1; i < high+1; i++) { for (int j = i; j > low; j--) { if (array[j].compareTo(array[j-1]) < 0) { swap(array, j, j-1); } else { break; } } } }
|