Chapter 2 Introduction to Algorithms
Merge two ordered arrays
The implementation of this algorithm is somewhat different from the implementation in the introduction to algorithms. I didn't use the Sentinel position method in introduction to algorithms. In addition, you can directly determine whether the array is at the end of the array. However, to stay consistent with the book, I still use the pseudo code in the introduction to algorithms.
Algorithm Description:
Merge (A, P, Q, R) stores data in a [p... q] And a [q + 1... r] The ordered subsequences in these two parts are merged into a [p... r] and make it orderly.
The length of the two sub-arrays is int n1 = Q-p + 1, int n2 = r-Q, and two new arrays L and R are created, used to store the two ordered parts of the original array respectively. Traverse two new arrays respectively, L and R, compare the elements in sequence, and store the smaller elements in the corresponding position of the original array. L after traversing any array in R, copy the rest of the other array to the position behind the original array. Now the algorithm is complete.
Pseudo-code implementation
Merge (A, P, Q, R) Introduction to algorithms 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) Introduction to algorithms 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 ++ code implementation
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 }