歸併排序演算法代碼

來源:互聯網
上載者:User

看資料結構書,看到歸併排序,便手動實現其代碼,發現普通的兩路歸併代碼是錯誤的,,,,不曉得原因是啥子。。。。

下表面的代碼是R.Sedgewick提出的一個改進的兩路歸併演算法代碼,經測試正確無誤。


void Merge(int L1[], int L2[], int first, int mid, int last)
{
    for(int i=first; i<=mid; i++)
        L2[i] = L1[i];
    int k = last;
    for(int j=mid+1; j<=last; j++)
//        L2[last+mid+1-j] = L1[j];
          L2[j] = L1[k--];
    int s1 = first;
    int s2 = last;
    int t = first;
    while(t<=last)
    {
        if(L2[s1] <= L2[s2])
            L1[t++] = L2[s1++];
        else
            L1[t++] = L2[s2--];
    }
}

void MergeSort(int L1[], int L2[], int first, int last)
{
    if(first>=last)
        return;
    int mid = (first+last)/2;
    MergeSort(L1, L2, first, mid);
    MergeSort(L1, L2, mid+1, last);
    Merge(L1, L2, first, mid, last);
}

int main()
{
    int L1[10] = {6,9,3,0,1,7,2,4,5,6};
    int L2[10];
    MergeSort(L1, L2, 0, 9);
    for(int i=0; i<10; i++)
        cout<<L1[i]<<endl;
    return 0;
}

聯繫我們

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