/**
* 快速排序(Quicksort)是对冒泡排序的一种改进。
* 由C. A. R. Hoare在1962年提出。
* 它的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,
* 其中一部分的所有数据都比另外一部分的所有数据都要小,
* 然后再按此方法对这两部分数据分别进行快速排序,
* 整个排序过程可以递归进行,以此达到整个数据变成有序序列。
* @author gulijiang
*
*/
public class Quicksort {
static int i = 0;
public static void main(String[] args) {
int[] a = {49, 38, 65, 97, 76, 13, 27};
sort(a, 0, a.length-1);
}
public static void sort(int[] a,int low,int high){
if(low >= high)
{
return;
}
//完成一次单元排序
int index = sortUnit(a, low, high);
//对左边单元进行排序
sort(a, low, index - 1);
//对右边单元进行排序
sort(a, index + 1, high);
}
public static int sortUnit(int[] a,int low,int high){
//记录次数
i++;
int key = a[low];
while (low < high) {
//从后向前搜索比key小的值
while (a[high] >= key && high > low) {
high --;
}
//比key小的放左边
if(low < high){
int temp = a[low];
a[low] = a[high];
a[high] = temp;
low++;
}
//从向前搜索比key大的值
while (a[low] <= key && high > low) {
low ++;
}
if(low < high){
int temp = a[low];
a[low] = a[high];
a[high] = temp;
high--;
}
}
System.out.println("第"+i+"趟排序完");
for (int j = 0; j < a.length; j++) {
System.out.print(a[j] +" ");
}
System.out.println("\n");
return high;
}
}