1. Brief Introduction
Assume that the array to be sorted is int array [] and the array length is N. Merge Sorting is a recursive method.
When N = 1, stop recursion.
When n> 1, open an array of the same size as array, int TMP []
Recursively sorts arrays from array [0] to array [n/2], recursively sorts arrays from array [n/2 + 1] to array [n-1 ].
Use two pointers to add the small elements to the TMP array one by one.
Copy TMP to array and release the TMP array.
2. Complexity
The average time complexity is O (n * logn), and the space complexity is O (n ).
Stability is a stable sorting. Note that when two pointers are compared in the program, if the sizes are the same, you should put the first pointer data in TMP, it can be ensured that the sorting is stable.
3. Code
Void merge_sort (int array [], int n ){
// Recursive termination
If (n <= 1)
Return;
// Recursive sorting
Merge_sort (array, n/2 );
Merge_sort (array + n/2, n-n/2 );
// Merge operations
Int * tmp = new int [n];
Int a = 0;
Int B = n/2;
Int I = 0;
While (a <n/2 & B <(n-n/2 )){
If (array [a] <= array [B]) // here <= ensures stability
Tmp [I ++] = array [a ++];
Else
TMP [I ++] = array [B ++];
}
While (A <n/2 ){
TMP [I ++] = array [A ++];
}
While (TMP [I ++] = array [A ++]) {
TMP [I ++] = array [B ++];
}
For (I = 0; I <n; I ++)
Array [I] = TMP [I];
Delete [] TMP;
}
The last two while statements and one for statement can be copied. You can use memcpy to speed up the process.
4. References
Wikipedia-merge sort http://en.wikipedia.org/wiki/Merge_sort