交換排序—快速排序(Quick Sort)

來源:互聯網
上載者:User

基本思想:

1)選擇一個基準元素,通常選擇第一個元素或者最後一個元素,

2)通過一趟排序講待排序的記錄分割成獨立的兩部分,其中一部分記錄的元素值均比基準元素值小。另一部分記錄的 元素值比基準值大。

3)此時基準元素在其排好序後的正確位置

4)然後分別對這兩部分記錄用同樣的方法繼續進行排序,直到整個序列有序。

快速排序是通常被認為在同數量級(O(nlog2n))的排序方法中平均效能最好的。但若初始序列按關鍵碼有序或基本有序時,快排序反而蛻化為冒泡排序。為改進之,通常以“三者取中法”來選取基準記錄,即將排序區間的兩個端點與中點三個記錄關鍵碼置中的調整為支點記錄。快速排序是一個不穩定的排序方法。

#include<iostream>#include<string>using namespace std;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 partion(int a[],int low,int high){    int privotekey=a[low];    while(low < high){        while(a[high] > privotekey) high--;        swap(a[low],a[high]);        while(a[low]< privotekey) low++;        swap(a[low],a[high]);    }    print(a,10);    return low;}void quickSort(int a[],int low,int high){    if(low < high){        int privotekey=partion(a,low,high);//每次把low位置的值作為基準值        quickSort(a,low,privotekey-1);        quickSort(a,privotekey+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);  }  

初始值:3 1 5 7 2 4 9 6 10 8
2 1 3 7 5 4 9 6 10 8
1 2 3 7 5 4 9 6 10 8
1 2 3 6 5 4 7 9 10 8
1 2 3 4 5 6 7 9 10 8
1 2 3 4 5 6 7 9 10 8
1 2 3 4 5 6 7 8 9 10
結果:1 2 3 4 5 6 7 8 9 10

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.