006.交換排序—快速排序(Quick Sort)
阿新 • • 發佈:2019-02-13
基本思想:
1)選擇一個基準元素,通常選擇第一個元素或者最後一個元素,
2)通過一趟排序講待排序的記錄分割成獨立的兩部分,其中一部分記錄的元素值均比基準元素值小。另一部分記錄的 元素值比基準值大。
3)此時基準元素在其排好序後的正確位置
4)然後分別對這兩部分記錄用同樣的方法繼續進行排序,直到整個序列有序。
快速排序的示例:
(a)一趟排序的過程:
(b)排序的全過程
演算法的實現:
遞迴實現:
- void print(int a[], int n){
- for(int j= 0; j<n; j++){
- cout<<a[j] <<" ";
- }
- cout<<endl;
- }
- void swap(int *a, int *b)
- {
- int tmp = *a;
- *a = *b;
- *b = tmp;
- }
- int partition(int a[], int low, int high)
- {
- int privotKey = a[low]; //基準元素
- while(low < high){ //從表的兩端交替地向中間掃描
- while(low < high && a[high] >= privotKey) --high;
- swap(&a[low], &a[high]);
- while(low < high && a[low] <= privotKey ) ++low;
- swap(&a[low], &a[high]);
- }
- print(a,10);
- return low;
- }
- void quickSort(int a[], int low, int high){
- if(low < high){
- int privotLoc = partition(a, low, high); //將表一分為二
- quickSort(a, low, privotLoc -1); //遞迴對低子表遞迴排序
- quickSort(a, privotLoc + 1, high); //遞迴對高子表遞迴排序
- }
- }
- int main(){
- int a[10] = {3,1,5,7,2,4,9,6,10,8};
- cout<<"初始值:";
- print(a,10);
- quickSort(a,0,9);
- cout<<"結果:";
- print(a,10);
- }
分析:
快速排序是通常被認為在同數量級(O(nlog2n))的排序方法中平均效能最好的。但若初始序列按關鍵碼有序或基本有序時,快排序反而蛻化為氣泡排序。為改進之,通常以“三者取中法”來選取基準記錄,即將排序區間的兩個端點與中點三個記錄關鍵碼居中的調整為支點記錄。快速排序是一個不穩定的排序方法。
快速排序的改進
在本改進演算法中,只對長度大於k的子序列遞迴呼叫快速排序,讓原序列基本有序,然後再對整個基本有序序列用插入排序演算法排序。實踐證明,改進後的演算法時間複雜度有所降低,且當k取值為 8 左右時,改進演算法的效能最佳。演算法思想如下
- void print(int a[], int n){
- for(int j= 0; j<n; j++){
- cout<<a[j] <<" ";
- }
- cout<<endl;
- }
- void swap(int *a, int *b)
- {
- int tmp = *a;
- *a = *b;
- *b = tmp;
- }
- int partition(int a[], int low, int high)
- {
- int privotKey = a[low]; //基準元素
- while(low < high){ //從表的兩端交替地向中間掃描
- while(low < high && a[high] >= privotKey) --high; //從high 所指位置向前搜尋,至多到low+1 位置。將比基準元素小的交換到低端
- swap(&a[low], &a[high]);
- while(low < high && a[low] <= privotKey ) ++low;
- swap(&a[low], &a[high]);
- }
- print(a,10);
- return low;
- }
- void qsort_improve(int r[ ],int low,int high, int k){
- if( high -low > k ) { //長度大於k時遞迴, k為指定的數
- int pivot = partition(r, low, high); // 呼叫的Partition演算法保持不變
- qsort_improve(r, low, pivot - 1,k);
- qsort_improve(r, pivot + 1, high,k);
- }
- }
- void quickSort(int r[], int n, int k){
- qsort_improve(r,0,n,k);//先呼叫改進演算法Qsort使之基本有序
- //再用插入排序對基本有序序列排序
- for(int i=1; i<=n;i ++){
- int tmp = r[i];
- int j=i-1;
- while(tmp < r[j]){
- r[j+1]=r[j]; j=j-1;
- }
- r[j+1] = tmp;
- }
- }
- int main(){
- int a[10] = {3,1,5,7,2,4,9,6,10,8};
- cout<<"初始值:";
- print(a,10);
- quickSort(a,9,4);
- cout<<"結果:";
- print(a,10);
- }