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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
| public class QuickSort {
public static void main(String[] args) { int[] array = { 8, 2, 5, 10, 7, 6, 15, 9, 12 }; for (int i : array) { System.out.print(i); System.out.print(","); } System.out.println(); sort(array, 0, array.length - 1); for (int i : array) { System.out.print(i); System.out.print(","); }
}
public static void sort(int[] array, int low, int high) { if (low < high) { int p = partion(array, low, high); sort(array, low, p - 1); sort(array, p + 1, high); } }
public static int partion(int[] array, int low, int high) { int middle = array[low]; while (low < high) { while (low < high && array[high] > middle) { high--; } array[low] = array[high]; while (low < high && array[low] < middle) { low++; } array[high] = array[low]; } array[low] = middle; return low; }
public static int partion2(int[] array, int low, int high) { int middle = array[low]; int index = low; low++; while (low < high) { while (low < high && array[high] > middle) { high--; } while (low < high && array[low] < middle) { low++; } if (low == high) { break; } else { exchangeElements(array, low, high); }
} exchangeElements(array, low, index); return low; }
public static void exchangeElements(int[] array, int index1, int index2) { if (array == null || array.length < 1) { throw new IllegalArgumentException("array can not be null or empty!"); } if (index1 < 0 || index2 < 0 || index1 > (array.length - 1) || index2 > (array.length - 1)) { throw new IllegalArgumentException("index must >0 and < array's size"); } if (index1 == index2) { return; } int temp = array[index1]; array[index1] = array[index2]; array[index2] = temp; }
}
|