Algorithm Overview/Ideas
The merge sort is based on a strategy known as divide and conquer. The basic idea is this:
1. For two ordered arrays, to be merged into an ordered array, we can easily write the following code:
Both A and B is ascend.
public void Merge (int[] A, int[] B, int[] c) {
int i=0,j=0,k=0;
while (I<=a.length && j<=b.length) {
if (A[i]<=b[i]) {
c[k++]=a[i++];
}
else{
c[k++]=b[j++];
}
while (i<=a.length) {
c[k++]=a[i++];
}
while (j<=b.length) {
c[k++]=b[j++];
}
}
It is easy to see that such a merging algorithm is efficient and its time complexity can reach O (n).
2. If there is a unordered array to be sorted, but its two completely divided sub arrays A and B are ordered, with the help of the above code, we can easily achieve;
3. So, what if a, B is unordered? You can divide them into smaller arrays.
4. So always to the smallest, each of which has only one element, it can be considered an ordered array.
5. Starting with these smallest arrays and merging them back against the above steps, the entire array is lined up.
In summary, the merge sort is to use recursion, first decompose the array into a child array, and then combine the array.
Example
The following example illustrates that if you want to sort the array a={2,1,3,5,2,3}, divide the arrays into {2,1,3} and {5,2,3} two substrings, which are sorted to {1,2,3} and {2,3,5}. Then the final ordered array is obtained by merging the two arrays. The code implementation is as follows:
void sort (int[] a) {
int[] aux = new int[a.length]; Auxiliary array
mergesort (A, 0, a.length-1, aux);
void MergeSort (int[] A, int lo, int hi, int[] aux) {
if (Hi <= lo) return
;
int mid = lo + (Hi-lo)/2;
MergeSort (A, lo, mid, aux);
MergeSort (A, mid + 1, Hi, aux);
Merge (A, lo, mid, Hi, aux);
}
void merge (int[] A, int lo, int mid, int hi, int[] aux) {
int i = lo, j = mid + 1;
for (int k = lo; k <= hi; k++) {
aux[k] = a[k];
}
for (int k = lo; k <= hi; k++) {
if (i > Mid)
a[k] = aux[j++];
else if (J > Hi)
a[k] = aux[i++];
else if (Aux[i] <= aux[j])
a[k] = aux[i++];
else
a[k] = aux[j++];
}
}
Another implementation: bottom-up merge sort
in the above implementation, the equivalent of a big problem divided into small problems, and then use all the answers to small questions to solve the whole big problem. Sorting a large array into decimal groups is a top-down sort. There is also an implementation is bottom-up sort, that is, 22 merge first, and then 44 merge ... The code implementation is as follows:
void sort (int[] a) {
int N = a.length;
int[] aux = new Int[n];
for (int sz = 1; sz < N; SZ + = SZ) {
for (int lo = 0; lo < N-sz; lo + + sz + sz) {
//in each round merge, the last merged second sub array may Smaller merges than the first sub array
(A, lo, lo + sz-1, Math.min (lo + sz + sz-1, N-1), aux);}