基本思想:通過一趟排序將要排序的數據分割成獨立的兩部分,其中一部分的所有數據都比另外一部分的所有數據都要小,然後再按此方法對這兩部分數據分別進行快速排序,整個排序過程可以遞歸進行,以此達到整個數據變成有序序列。
public class QuickSort {
public static void main(String[] args) {
//測試數據
int[] iArgs = {5,4,9,2,8,3,1,7};
int left = 0; //數組第一個位置
int right = iArgs.length - 1;//數組最後一個位置;
QuickSort quickSort = new QuickSort();
//快速排序
quickSort.recursive(iArgs,left,right);
//輸出數組
for(int i = 0; i < iArgs.length; i++) {
System.out.print(iArgs[i] + " ");
}
}
/**
* 遞歸循環數據
*
* @param args 數組
* @param left 數組左下標
* @param right 數組右下標
* @return
*/
private void recursive(int[] args,int left,int right) {
if( left < right) {
//數據從left到right座標的數據進行排序
int iIndex = qucikSort(args,left,right); //iIndex 是基數放在數據位置
//遞歸算法,對於基數左邊排序
recursive(args,left,iIndex-1); //爲什麼left不能從0
//遞歸算法,對於基數右邊排序
recursive(args,iIndex+1,right);//爲什麼 right不等於length
}
}
/**
* 確定基數左邊的數都比它小,右邊的數都比它大
*
* @param args 數組
* @param left 數組左下標
* @param right 數組右下標
* @return
*/
private int qucikSort(int[] args,int left,int right) {
int iBase = args[left];; //基準數
while (left < right) {
//從右向左找出第一個比基準數小的數
while( left < right && args[right] >= iBase) {
right--;
}
args[left] = args[right];
//從左向右找出第一個比基準數小的數
while( left < right && args[left] <= iBase) {
left++;
}
args[right] = args[left];
}
args[left]= iBase;
return left;
}
}
另一種寫法:
public class QuickSort {
/**
* @param args
*/
public static void main(String[] args) {
int[] array = {10, 20, 15 , 16, 18 , 17, 12, 13, 19, 11, 14};
QuickSort(array, 0, array.length - 1);
for(int i = 0; i < array.length; i++){
System.out.print(array[i]+" ");
}
}
private static void QuickSort(int[] array, int low, int high) {
if(low < high){
int position = Partition(array, low, high);
QuickSort(array, low, position-1);
QuickSort(array, position+1, high);
}
}
private static int Partition(int[] array, int low, int high) {
int start = low;
int end = high + 1;
int compare = array[low];
int tmp;
while(true){
while(array[++start] < compare && start < high);
while(array[--end] > compare);
if(start >= end) break;
tmp = array[start];
array[start] = array[end];
array[end] = tmp;
}
array[low] = array[end];
array[end] = compare;
return end;
}
}