Divide and conquer is the core idea of merge sort. You can recursively divide the original array into two sub-arrays, until each sub-array only has one element. At the last, it looks like a tree, the root node is the original array and the leaf node is the array which only has one element. Then from bottom to up, merge two adjacent arrays from the same level, and organize them into an ordered array.
The detail steps of this algorithm are as follows:
1. Calculate the element position in middle.
2. Separate the original array to two sub-arrays, one is from start to the middle position and the other is from the position next the middle one to the end of the array. Make the two sub-arrays as the new argument and then call the merge sort method itself respectively.
3. Merge the two sub-arrays and ensure that the merge result is ordered.
How to make sure the merge result is ordered?
Firstly, we should clearly know that each sub-array had been ordered.
Then, choose the first element of each sub-array, and then compare the two elements, put the smaller element to the result array, and then we should get the next element from the array in which the smaller element is located.
If one of the sub-arrays are empty, then add the rest elements of the other sub-arrays to the end of the result array.
4. Quit the recursion if the end position is less than the start position.
Its time complexity is O(nlgn).
The following is the implement of merge-sort by java.
public void mergeSort(int[] A, int s, int e){
if(s < e){
int m = (e + s)/2;
mergeSort(A,s,m);
mergeSort(A,m+1,e);
mergeSorted(A,s,m,e);
}
}
private void mergeSorted(int[] A,int s, int m,int e){
int[] L = new int[m-s+1];
int[] R = new int[e-m];
for(int i = 0;i < L.length;i++){
L[i] = A[s+i];
}
for(int j = 0;j < R.length;j++){
R[j] = A[m+1+j];
}
int i = 0,j = 0;
for(int k = s;k < e-s+1;k++){
if(i > L.length - 1){
A[k] = R[j];
j++;
}else if(j > R.length - 1 ||L[i] <= R[j]){
A[k] = L[i];
i++;
}else{
A[k] = R[j];
j++;
}
}
}