初始数组: 5,2,9,3,8,4,0,1,6,7
主元: 5
初始数组被分区: 4,2,1,3,0,5,8,9,6,7
a) 4,2,1,3,0
b) 8,9,6,7
对a)快排:
a) 4,2,1,3,0
主元:4
分区:0,2,1,3,4
c) 0,2,1,3
对c)快排:
c) 0,2,1,3
主元:0
d) 2,1,3
对d)快排:
1,2,3
算法实现:
publicclass QuickSort {
publicstaticvoid main(String[] args) {
int[] list = { 2, 3, 2, 5, 6, 1, -2, 3, 14, 12 };
quickSort(list);
System.out.print("{2,3,2,5,6,1,-2,3,14,12}" + " by insertionSort is {");
for (int i = 0; i < list.length; i++) {
System.out.print(list[i] + ",");
}
System.out.println("}");
}
publicstaticvoid quickSort(int[] list) {
quickSort(list, 0, list.length - 1);
}
publicstaticvoid quickSort(int[] list, int first, int last) {
if (last > first) {
int pivotIndex = partition(list, first, last);
quickSort(list, first, pivotIndex - 1);
quickSort(list, pivotIndex + 1, last);
}
}
publicstaticint partition(int[] list, int first, int last) {
int pivot = list[first];
int low = first + 1;
int high = last;
while (high > low) {
// search forward from leftwhile (low <= high && list[low] <= pivot)
low++;
// Search backward from rightwhile (low <= high && list[high] > pivot)
high--;
// Swap two elements in the listif (high > low) {
int temp = list[high];
list[high] = list[low];
list[low] = temp;
}
}
while (high > first && list[high] >= pivot)
high--;
// Swap pivot with list[high]if (pivot > list[high]) {
list[first] = list[high];
list[high] = pivot;
return high;
} elsereturn first;
}
}