基本思想:(挖坑填数+分治法)
1)选择一个基准元素,通常选择第一个元素或者最后一个元素,
2)通过一趟排序讲待排序的记录分割成独立的两部分,其中一部分记录的元素值均比基准元素值小。另一部分记录的 元素值比基准值大。
3)此时基准元素在其排好序后的正确位置
4)然后分别对这两部分记录用同样的方法继续进行排序,直到整个序列有序。
快速排序的示例:
(a)一趟排序的过程:
(b)排序的全过程
具体实现:
package sort;
import test.Utils;
public class QuickSort {
public static void main(String[] args) {
int a[] = { 5, 8, 6, 4, 1, 3, 2, 7, 0, 9 };
quickSort(a, 0, a.length - 1);
}
public static void quickSort(int[] a, int lift, int right) {
if (lift < right) {
int low = lift;
int high = right;
int pivot = a[lift];
while (low < high) {
while (low < high && a[high] >= pivot)
high--;
if (low < high)
a[low++] = a[high];
while (low < high && a[low] < pivot)
low++;
if (low < high)
a[high--] = a[low];
}
a[low] = pivot;
Utils.printf(a);
quickSort(a, lift, low - 1);
quickSort(a, high + 1, right);
}
}
}