《演算法導論》CLRS演算法C++實現(二)P17 歸併排序

來源:互聯網
上載者:User

第二章 演算法入門

兩個有序數組的合并

這個演算法我的實現跟演算法導論上的實現有些許區別。我沒有使用《演算法導論》上的哨兵位的方法。而且直接判斷有沒有到數組的末尾。不過為了跟書上保持一致,我的虛擬碼還是使用演算法導論上的虛擬碼。

演算法描述:

MERGE(A, p, q, r)是把儲存在A[p...q]和A[q+1...r]這兩部分中的有序子序列合并到A[p...r]並使其有序。

兩個子數組的長度分別為int n1=q-p+1; int n2=r-q; 建立兩個新數組L和R,用於分別存放原數組的兩個有序部分。分別遍曆兩個新的數組L和R,依次比較其中元素,將其中較小的元素存放到原數組A的對應位置。L和R中任何一個數組遍曆結束後,將另一個數組的剩餘部分複製到原數組A的後面位置。至此演算法完成。

虛擬碼實現

MERGE(A, p, q, r)  《演算法導論》P17

 1 n1 ← q - p + 1 2 n2 ← r - q 3 create arrays L[1 ‥ n1 + 1] and R[1 ‥ n2 + 1] 4 for i ← 1 to n1 5     do L[i] ← A[p + i - 1] 6 for j ← 1 to n2 7     do R[j] ← A[q + j] 8 L[n1 + 1] ← ∞ 9 R[n2 + 1] ← ∞10 i ← 111 j ← 112 for k ← p to r13     do if L[i] ≤ R[j]14         then A[k] ← L[i]15             i ← i + 116         else A[k] ← R[j]17             j ← j + 1

MERGE-SORT(A, p, r)  《演算法導論》 P19

1 if p < r2     then q ← floor((p + r)/2)3         MERGE-SORT(A, p, q)4         MERGE-SORT(A, q + 1, r)5         MERGE(A, p, q, r)

C++代碼實現

 1 #include <iostream> 2  3 using namespace std; 4  5 void merge(int*arr, int p, int q, int r) 6 { 7     int n1 = q - p + 1; 8     int n2 = r - q; 9 10     int* L = new int[n1];11     int* R = new int[n2];12 13     for(int i = 0; i < n1; i++)14     {15         L[i] = arr[p + i];16     }17     for(int j = 0; j < n2; j++)18     {19         R[j] = arr[q + j + 1];20     }21 22     int i = 0;23     int j = 0;24     int k = p;25 26     while((i < n1) && (j < n2))27     {28         if(L[i] <= R[j])29         {30             arr[k] = L[i];31             i++;32         }33         else34         {35             arr[k] = R[j];36             j++;37         }38         k++;39     }40 41     if (i < n1)42     {43         for(; i < n1; i++, k++)44         {45             arr[k] = L[i];46         }47     }48     if (j < n2)49     {50         for(; j < n2; j++, k++)51         {52             arr[k] = R[j];53         }54     }55 }56 57 void mergesort(int* arr, int p, int r)58 {59     int q = 0;60     if(p < r)61     {62         q = (p + r) / 2;63         mergesort(arr, p, q);64         mergesort(arr, q + 1, r);65         merge(arr, p, q, r);66     }67 }68 69 int main()70 {71     int a[] = {2, 45, 5, 7, 34, 456, 345, 89, 8, 1, 341, 4, 98, 67};72     mergesort(a, 0, 13);73     for(int i = 0; i < 14; i++)74     {75         cout << a[i] << " ";76     }77     cout << endl;78     return 0;79 }
相關文章

聯繫我們

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