Quick Sort 的演示:
1)随机取一个pivot(通常习惯是数组的最后一个元素)
快速排序的中心思想是找一个pivot(具体的数组的一个值,而非坐标),pivot是一个枢纽意思。之所谓枢纽,就是要每次按照这个pivot给出一个partition index(wall)。在这个partition index的之前的都必须小于pivot,而在partition index之后的都是需要大于pivot。所以,不用说,partition index本身的大小就是pivot。
所以,一次上述的partition 过程确保了pivot在一个正确的位置上,而其它的元素不一定。
2)根据所给的pivot,把原数组分为左右两边。因为pivot的位置是已经确定了,所以不用管pivot。而对左右两边的子数组递归调用QuickSort。
假如给出如下的数组: | 6 3 4 2 1 7 5
QuickSort的解法如下:
1) pivot = 5; partition index = 0; 比较:6放在patition index右边,所以不用动。3小于Pivot,所以要和当前的partition index (0)值交换:
3 | 6 4 2 1 7 5 (partition index ++)
接着4 小于 5: 3 4 | 6 1 7 5
接着1 小于 5: 3 4 1 | 6 7 5
接着扫到最后,因为 5 == 5(从start 到 end,判断条件是 a[index] <= pivot就交换): 3 4 1 5 6 7。这时候5实质是partition index.
2) 对 [3 4 1] 和 [6 7]分别调用Quicksort. 得到[1] [4 3] 和 [6] [7]。递归的终止条件是当前的子数组只有一个元素的时候。
3) 得到[1] [3] [4] [6] [7]。这时候递归终止,返回。(只是原数组的in place swap)。
Quick sort的理想、一般复杂度是O(nlogn),每次分完之后要和n次比较。而分多少次则取决于你每次的pivot选得好不好。如果选得好,一般只用分logn次。但如果选择不好,每次的end都是最大值或者最小值,则需要分n次。总的复杂度是O(n^2).
Quicksort的Java代码:
public class QuickSortClass {
private void swap(int[] src, int left, int right) {
int tmp = src[left];
src[left] = src[right];
src[right] = tmp;
}
private int partition(int[] src, int start, int end) {
int pivot = src[end];
int partitionIndex = start;
int index = start;
while (index < end) {
if (src[index] <= pivot) {
swap(src, index, partitionIndex);
partitionIndex = partitionIndex + 1;
}
index = index + 1;
}
swap(src, end, partitionIndex);
return partitionIndex;
}
public void quickSort(int[] src, int start, int end) {
if (start >= end) {
return;
}
int partitionIndex = partition(src, start, end);
quickSort(src, start, partitionIndex - 1);
quickSort(src, partitionIndex + 1, end);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] input = new int[]{6,4,2,3,1,5,7};
QuickSortClass ins = new QuickSortClass();
ins.quickSort(input, 0, input.length - 1);
for (int tmp : input) {
System.out.println(tmp);
}
}
}