快速排序的基本思想是利用一輪排序讓待排記錄分爲兩部分,其中一部分均比另一部分小,然後再分別對兩部分採用相同的思想進行排序。假設待排爲一數組,首先任意選取一個記錄(通常選擇第一個記錄)作爲樞軸,然後按下述原則重新排列記錄:將所有關鍵字較它小的記錄都安置在它的位置之前,將所有關鍵字都較它大的記錄都安置在它的位置之後。這個過程即爲一輪快速排序。
就平均時間而言,該算法具有較高效率(O(nlogn))。但當待排序記錄的關鍵字有序或基本有序時,該算法退化爲起泡排序,時間複雜度爲O(n2)。
爲改進之,引入隨機化的思想,及樞軸的位置並非始終爲第一個記錄,而是隨機的選擇一個記錄作爲樞軸。具體代碼如下:
import java.util.Random;
public class RQuickSort {
public RQuickSort() {
// TODO Auto-generated constructor stub
}
public void RQSort(int []a, int low, int hight) {
if(low < hight){
int pivotkey = Partition(a, low, hight);
RQSort(a, low, pivotkey-1);
RQSort(a, pivotkey+1, hight);
}
}
public int Partition(int [] a , int low, int hight){
//隨機的給出樞軸的位置
Random random = new Random();
int index = random.nextInt(hight-low+1)+low;
int temp = a[index];
a[index] = a[low];
a[low] = temp;
int pivotkey = a[low];
while(low < hight){
while(low<hight && a[hight] >= pivotkey)
--hight;
int k = a[hight];
a[hight] = a[low];
a[low] = k;
while(low<hight && a[low] <= pivotkey)
++low;
k = a[low];
a[low] = a[hight];
a[hight] = k;
}
return low;
}
}