非遞迴歸併排序(二路合并排序),非遞迴合并排序

來源:互聯網
上載者:User

 google了一下沒找到像樣的(實現太複雜,太低效),自己寫一個發出來。以後還是要多貼些東西吧,不然部落格很空! 下面的如果有可以改進的地方,表忘了告訴我。

自底向上的歸併排序,舉個例子吧還是:
現在要把下面的數組按遞增順序排列
9 8 7 6 5 4 3 2 1   

step1:(len=1) 8 9    6 7    4 5    2 3    1
step2:(len=2) 6 7 8 9    2 3 4 5    1
step3:(len=4) 2 3 4 5 6 7 8 9    1
step4:(len=8) 1 2 3 4 5 6 7 8 9

每次歸併分組都有空格隔開了的,其中len的意思是:把數組中長度為len的相鄰的兩段進行合并,當len大於數組長度是結束。

so easy! 應該容易理解吧. 具體實現見下面代碼。 

 

 

template <class T, class C>void msort( T* table, const int& size, C cmp ){int flag = 0;T* tmp = new T[size];T* src;T* dst;int b1, b2, e1, e2, len, index, di;for( len = 1; len <= size; len *= 2 ) //! O(logn){if( flag % 2 == 0 ) src = table, dst = tmp;else src = tmp, dst = table;for( index = 0; index < size; index += ( len<<1 ) ) //! O(n){if( index + len > size ){for( di = index; di < size; di++ ) dst[di] = src[di];break;}b1 = index, b2 = index + len, e1 = b1 + len, e2 = b2 + len, di = index;if( e2 > size ) e2 = size;while( b1 < e1 && b2 < e2 )dst[di++] = cmp( src[b1] ,src[b2] ) ? src[b1++] : src[b2++];while( b1 < e1 )dst[di++] = src[b1++];while( b2 < e2 )dst[di++] = src[b2++];}flag++;}if( flag % 2 == 1 )memcpy( table, dst, sizeof( int ) * size );delete [] tmp;}

test code:

bool cmp( const int& a, const int& b ) { return a < b; }int main(){int hsize = 20;int testa[20] = \
            { 17 , 92, 3, 88, 5, 6, 7, 8, 9, 40, 11, 12, 13, 14, 25, 16, 87, 18, 19, 20 };msort( testa, hsize, cmp );for( int i = 0; i < hsize; i++ )std::cout<<testa[i] << " ";std::cout<< "\n";return 0;}

 

要正式用的話,還應該自己實現記憶體 Clerk,不想太複雜,調用又很頻繁地話,直接傳緩衝進去吧

聯繫我們

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