The main idea of merge sort is:
- Divide array into two halves
- Recursively sort each half
Merge two half
The purpose of Merge operation is “Given two sorted sub arrays a[lo] to a[mid] and a[mid+1] to a[hi], replace the sorted subarray a[lo] to a[hi]”
So The Merger Operation is as following:
public static void merge(int[] a, int[] aux, int lo, int mid, int hi){
// a[lo ... mid] and a[mid ... hi] have been sorted
for(int k=lo;k<=hi;k++){
aux[k] = a[k]; //copy all the element in a to array-aux
}
int i = lo;
int j = mid+1;
// i scans the first array, j scans the second; k scans the whole
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[j]<aux[i]) a[k] = aux[j++];
else a[k] = aux[i++];
}
}
The Sort Operation is :
// This is easy to understand, sort the first half, afterwards sort the second half. At last, merge them together
public void sort(int[] a, int[] aux, int lo, int hi){
if(hi <= lo) return;
int mid =lo + (hi - lo) / 2;
sort(a,aux,lo,mid);
sort(a,aux,mid+1,hi);
merge(a,aux,lo,mid,hi);
}
Test case:
public class sort {
public static void main(String[] args){
int[] a = {1,9,5,7,3,0,6,2,4,13,16,15};
int[] aux = new int[a.length];
merge m = new merge();
m.sort(a,aux,0,a.length-1);
for(int i=0;i<a.length; i++){
System.out.print(a[i]+" ");
}
}
// result: 0 1 2 3 4 5 6 7 9 13 15 16
}