Principles of Merge Sorting:
If the number of elements in the array is greater than 1, then:
Divide the array into two parts equally;
Array merging and sorting on the left; Recursion
Array merging and sorting on the right; Recursion
Merge two sorted arrays. An additional secondary array is required to save the merging result temporarily.
Otherwise, when the number of array elements is 1, it is ordered; return directly.
Stable sorting. The time complexity is O (n lgn) at the worst, best, and average, and the space complexity is O (n ).
Code:
1 # include <iostream> 2 using namespace STD; 3 4 template <typename T> 5 void mergesortedarray (t src [], int first, int mid, int last, t TMP []) 6 {7 int I = first, j = Mid + 1; 8 int idx = 0; 9 10 while (I <= Mid & J <= last) 11 {12 TMP [idx ++] = SRC [I] <SRC [J]? SRC [I ++]: SRC [J ++]; 13} 14 15 while (I <= mid) 16 {17 TMP [idx ++] = SRC [I ++]; 18} 19 while (j <= last) 20 {21 TMP [idx ++] = SRC [J ++]; 22} 23 24 for (I = 0; I <idx; ++ I) 25 {26 SRC [first + I] = TMP [I]; 27} 28} 29 30 template <typename T> 31 void mergesort (T SRC [], int first, int last, t TMP []) 32 {33 If (first> = last) 34 return; 35 36 int mid = first + (last-first)> 1 ); // locate the subscript of the intermediate element and divide the array into two parts: 37 38 mergesort (SRC, first, mid, TMP); // sort the left-side sub-array 39 mergesort (SRC, Mid + 1, last, TMP); 40 41 mergesortedarray (SRC, first, mid, last, TMP); // merge, TMP is the auxiliary array, result 42} 43 44 int main () 45 {46 const int n = 5; 47 48 int Ia [N] = {1, 3, 6, 2, 4}; 49 int itmp [N]; 50 mergesort (IA, 0, n-1, itmp); // sort51 for (INT I = 0; I <N; ++ I) 52 cout <Ia [I] <''; 53 cout <Endl; 54 55 double da [N] = {1.2, 3.4, 6.7, 2.3, 4.5}; 56 double dtmp [N]; 57 mergesort (DA, 0, n-1, dtmp); // sort58 for (INT I = 0; I <N; ++ I) 59 cout <da [I] <''; 60 cout <Endl;
61 Return 0;
62}