快速排序(Quick Sort)
基本思想:
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; //從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 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);
- }
- 轉:http://blog.csdn.net/cangchen/article/details/44816905