快速排序是基于分治策略的一种排序算法。基本思想是对输入的数组z[left, right] 按以下2个步骤进行排序:
1)分解: 以 a[left] 为基准元素,将a[left,right] 划分为3段, a[left, q-1], a[q], a[q+1, right], 使得a[left, q-1]中的任何元素都小于等于a[q], a[q+1, right]中任何元素都大于等于 a[q]; q在划分过程中确定;
2)递归求解: 对a[left, q-1], a[q+1, right] 分别进行排序;a[left, q-1], a[q+1, right]的排序都是就地完成的;
对《算法设计与分析》第四版 P31代码改进成可运行程序。
package ch02.book;
public class QuickSort {
static boolean debug = true;
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = {11,38,65,97,76,13,27,49};
System.out.print("Before sort: ");
displayArray(arr);
qSort(arr, 0, arr.length-1);
System.out.print("After sort: ");
displayArray(arr);
}
public static void displayArray(int[] arr) {
if (debug) {
for (int i = 0; i < arr.length; i++) {
System.out.printf("%4d", arr[i]);
}
System.out.println();
}
}
public static void qSort(int[] arr, int left, int right) {
if (debug) System.out.printf("sort sub-arr [%d, %d]\r\n", left, right);
if (left< right) {
int interm = partition(arr, left, right);
qSort(arr, left, interm-1);
qSort(arr, interm + 1, right);
}
}
public static int partition(int[] arr,int interm, int right) {
if (debug) System.out.printf("partition for sub-arr[ %d, %d]\r\n", interm, right);
int low = interm, high = right + 1 ;
int flag = arr[interm];
//int flag = arr[right];
while(low < high) {
while(arr[++low] < flag && low <right) ;
while (arr[--high] > flag );
// find elements that satisfy: arr[low]>= flag and arr[high] <= flag;
// then switch these two elements;
if (low >= high) {
break;
}
if (debug) System.out.printf("find arr[%d]:%d >= arr[%d]:%d >= arr[%d]:%d, exchange arr[%d] and arr[%d]:\r\n", low, arr[low],interm,arr[interm], high, arr[high], low, high);
int temp = arr[low];
arr[low] = arr[high];
arr[high]= temp;
displayArray(arr);
}
if (debug) {
System.out.printf("partition complete , exchange arr[%d]: %d and arr[%d]:%d\r\n", interm, arr[interm], high, arr[high]);
}
arr[interm] = arr[high];
arr[high]= flag;
displayArray(arr);
if (debug) System.out.printf("get interim %d\r\n", high);
return high;
}
}
测试数据运行结果:
Before sort: 11 38 65 97 76 13 27 49
After sort: 11 13 27 38 49 65 76 97
通过开启debug标志位可以观察排序的过程;