幾種常見的排序演算法

來源:互聯網
上載者:User

1、冒泡排序

演算法描述:

代碼實現:

void bubble_sort(int* a ,int n){bool changed;do{changed = false;for(int i = 1 ; i < n ; ++i){if(a[i] < a[i-1]){swap(a[i],a[i-1]);changed = true;}}}while(changed);}

2、插入排序

演算法描述:

代碼實現:

void insert_sort(int* a , int n){for(int i = 1; i < n ; ++i ){int t  = a[i];int j;for( j = i ; j > 0 && t < a[j-1]; --j){a[j] = a[j-1];}a[j] = t;}}

3、快速排序

演算法流程說明:

代碼實現:

void quick_sort(int* a , int n){if( n <= 1){return ;}if( n== 2){if(a[1] < a[0]){swap(a[1],a[0]);}}swap(a[n/2],a[0]);int jie = a[0];int* l = a + 1;int* r = a + n - 1;while( l < r ){while(l<r && (*l < jie)){++l;}while(a<r && (*r>=jie)){--r;}if(l < r){swap(*l,*r);}}if(*r < jie){swap(*r,a[0]);}quick_sort(a,r-a);quick_sort(r+1,n-1-(r-a));}

4、選擇排序

代碼實現:

void choose_sort(int* a , int n){for(int i = 0 ; i < n -1 ; ++i ){int min = i;for(int j = i+1 ; j < n ; ++j ){if(a[j] < a[min]){min = j;}}swap(a[i],a[min]);}}

演算法描述:

聯繫我們

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