快速排序的遞迴和非遞迴實現 -----C++代碼實現

來源:互聯網
上載者:User

標籤:遞迴   partition   快速排序   

快速排序的基本思想是:通過一趟排序將待排記錄分割成獨立的兩部分,其中一部分記錄的關鍵字均比另一部分記錄的關鍵字小,則可分別對這兩部分記錄繼續進行排序,已達到整個序列有序.
快速排序是一種不穩定的排序方法,其平均時間複雜度為:O(NlogN),最壞的情況是O(N*N)
特別注意:快速排序中用到的Partition函數,它的作用是進行一趟快速排序,返回“參考目標”的最終位置p,經過Partition處理之後,p左邊的記錄關鍵字均不大於參考目標,p右邊的記錄關鍵字均不小於參考目標。 Partition函數在找出數組中最大或最小的k個記錄也很有用.
C++代碼如下:

#include <iostream>#include <vector>#include <stack>using namespace std;template <typename Comparable>int partition(vector<Comparable> &vec,int low, int high){    Comparable pivot = vec[low];    while (low<high)    {        while (low<high && vec[high]>=pivot)        {            high--;        }        vec[low] = vec[high];        while (low <high&&vec[low]<=pivot)        {            low++;        }        vec[high] = vec[low];    }    vec[low] = pivot;    return low;}//使用遞迴快速排序template<typename Comparable>void quicksort1(vector<Comparable> &vec,int low ,int high){    if (low <high)    {        int mid = partition(vec, low, high);        quicksort1(vec, low, mid - 1);        quicksort1(vec, mid + 1, high);    }}//其實就是用棧儲存每一個待排序子串的首尾元素下標,下一次while迴圈時取出這個範圍,對這段子序列進行partition操作,//每次得到的mid都是vector的最終位置,知道棧中不需要放入,也沒有資料時,迴圈結束template<typename Comparable>void quicksort2(vector<Comparable> &vec, int low, int high){    stack<int> st;    if (low<high)    {        int mid = partition(vec, low, high);        if (low<mid-1)        {            st.push(low);            st.push(mid - 1);        }        if (mid+1<high)        {            st.push(mid + 1);            st.push(high);        }        while (!st.empty())        {            int q = st.top();            st.pop();            int p = st.top();            st.pop();            mid = partition(vec, p, q);            if (p<mid-1)            {                st.push(p);                st.push(mid - 1);            }            if (mid+1<q)            {                st.push(mid + 1);                st.push(q);            }        }    }}int _tmain(int argc, _TCHAR* argv[]){    int a[10] = { 12, 21, 33, 4, 50, 62, 71, 52,111,9 };    vector<int> vec(a, a + 10);    int len = vec.size();    //quicksort1(vec, 0, len - 1);    quicksort2(vec, 0, len - 1);    for (int i=0; i < len;i++)    {        cout << vec[i]<< endl;    }    system("pause");    return 0;}

快速排序的遞迴和非遞迴實現 -----C++代碼實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.