歸併排序演算法C++的實現

來源:互聯網
上載者:User
#include <iostream>using namespace std;void merge(int a[], int first, int mid, int last, int c[]){    int i = first,j = mid + 1;     int m = mid, n = last;    // k 的值與 i的值必須相等,要不無法把c的值回寫給a    int k = first;    //都還沒有到數組的頭    while (i<=m && j<=n)    {        if (a[i] <=  a[j])        {            //新數組加插入較小的元素            c[k++] = a[i++];        }        else        {            c[k++] = a[j++];        }    }    //如果i的部分還沒有完全插入到數組就將剩餘部分加入    if (i <= m) {        while (i<=m)            c[k++] = a[i++];    }    if (j <= n) {        while (j<=n)            c[k++] = a[j++];    }    //回寫資料給a,如果不回寫,a就永遠不會被排序    for(int i=first;i<=last;i++)        a[i] = c[i];}void mergeSort(int a[], int first, int last,  int temp[]){    if (first < last)    {        int mid = (last + first) / 2;        mergeSort(a, first, mid, temp);        mergeSort(a, mid+1, last, temp);        merge(a, first, mid, last, temp);    }}int main(){    int a[] = {3, 20, 32, 90, 23, 41, 5, 3, 6, 4, 7, 5, 7, 4};    int b[sizeof(a) / sizeof(*a)];    mergeSort(a, 0, sizeof(a) / sizeof(*a), b);    //output    for(int i=0; i<sizeof(a) / sizeof(*a); i++)        cout << b[i] << ' ';    cout << endl;    return 0;}

參考:

http://baike.baidu.com/view/90797.htm

http://zh.wikipedia.org/wiki/%E5%BD%92%E5%B9%B6%E6%8E%92%E5%BA%8F

http://blog.csdn.net/morewindows/article/details/6678165

聯繫我們

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