快速排序—-非遞迴

來源:互聯網
上載者:User

我們以前寫快排都是寫遞迴的。

#include<iostream>#include<vector>#include<stack>#include<stdlib.h>#include<algorithm>#include <time.h>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];    }    //此時low==high    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);    }}/**使用棧的非遞迴快速排序**/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迴圈時取出這個範圍,對這段子序列進行partition操作        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 main(){    int len=1000000;    vector<int> vec;    for(int i=0;i<len;i++){vec.push_back(rand()); }    clock_t t1=clock();    quicksort1(vec,0,len-1);    clock_t t2=clock();    cout<<"recurcive  "<<1.0*(t2-t1)/CLOCKS_PER_SEC<<endl;    //重新打亂順序    random_shuffle(vec.begin(),vec.end());    t1=clock();    quicksort2(vec,0,len-1);    t2=clock();    cout<<"none recurcive  "<<1.0*(t2-t1)/CLOCKS_PER_SEC<<endl;    return 0;}

 

今天突然想起來,若是讓你改成非遞迴,該咋寫呢。

在網上找了個。

運行結果是:

recurcive  4.932
none recurcive  7.959
請按任意鍵繼續. . .

 

可以看到非遞迴的演算法比遞迴實現還要

下面解釋為什麼會這樣。

遞迴演算法使用的由程式自動產生,棧中包含:函數調用時的參數和函數中的局部變數

如果局部變數很多或者函數內部又調用了其他函數,則棧會很大。

每次遞迴調用都要操作很大的棧,效率自然會下降。

而對於非遞迴演算法,每次迴圈使用自己預先建立的棧,因此不管程式複雜度如何,都不會影響程式效率。對於上面的快速排序,由於局部變數只有一個mid,棧很小,所以效率並不比非遞迴實現的低。

 

 

聯繫我們

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