資料結構基礎(5),資料結構基礎

來源:互聯網
上載者:User

資料結構基礎(5),資料結構基礎

歸併排序的基本思想:

    將兩個或兩個以上的有序子序列”歸併”為一個有序序列:假定待排序表含有n個記錄, 則可以看成是n個有序的子表, 每個子表長度為1, 然後兩兩歸併, 得到[n/2]個長度為2或1的有序表,; 再量量歸併, ...., 如此重複, 直到合并成為一個長度為n的有序表為止, 這種排序方法稱為2-路歸併排序.為一個2-路歸併排序的一個樣本:


/**說明:將有序的記錄序列 initList[left:mid] 和 initList[mid+1:right]歸併為有序的記錄序列 initList[left:right]    initList:  原始的有序序列[分為兩段]    tmpList:  合并過程中需要的中間序列    left:       initList最左邊元素的下標    mid:        指向第一個有序序列的最後一個元素的下標    right:      initList最右邊元素的下標*/template <typename Type>int Merge(Type *initList, Type *tmpList, int left, int mid, int right){    //先將待歸併的數組複製到tmpList中去    std::copy(initList+left, initList+right+1, tmpList+left);//    同下://    for (int i = left; i <= right; ++i)//    {//        tmpList[i] = initList[i];//    }    int s1 = left, s2 = mid+1;    int iResult = left;    while (s1 <= mid && s2 <= right)    {        if (tmpList[s1] <= tmpList[s2])        {            initList[iResult ++] = tmpList[s1 ++];        }        else        {            initList[iResult ++] = tmpList[s2 ++];        }    }    int *end;    if (s1 <= mid)        end = std::copy(tmpList+s1, tmpList+mid+1, initList+iResult);    if (s2 <= right)        end = std::copy(tmpList+s2, tmpList+right+1, initList+iResult);    return end - (initList+left);//    同下:其實這兩個迴圈只有一個會執行//    while (s1 <= mid)//    {//        initList[iResult ++] = tmpList[s1 ++];//    }//    while (s2 <= right)//    {//        initList[iResult ++] = tmpList[s2 ++];//    }////    return iResult;}
//二路歸併排序-遞迴演算法template <typename Type>void mergeSort(Type *initList, Type *tmpList, int left, int right){    if (left >= right)        return;    int mid = (left+right)/2;    mergeSort(initList, tmpList, left, mid);    //先將左邊元素排序    mergeSort(initList, tmpList, mid+1, right); //後將右邊元素排序    Merge(initList, tmpList, left, mid, right); //合并}

可以看出對n個記錄進行歸併排序的時間複雜度為Ο(nlogn)。即:

    (1)每一趟歸併(合并)的時間複雜度為 O(n);

    (2)總共需進行[logn]趟。

聯繫我們

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