Code:
public class MergeSort {
public static void main(String...args) {
int[] a = new int[] {1, 3, 9, 2, 6, 0};
MergeSort ms = new MergeSort();
ms.sort(a);
for(int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
public void sort(int[] a) {
sort(a, 0, a.length - 1);
}
private void sort(int[] a, int lo, int hi) {
int mid = lo + (hi - lo)/2;
if(lo >= hi) return;
sort(a, lo, mid);
sort(a, mid + 1, hi);
merge(a, lo, mid, hi);
}
private void merge(int[] a, int lo, int mid, int hi) {
int[] aux = new int[a.length];
for(int i = lo; i <= hi; i++) {
aux[i] = a[i];
}
int i = lo;
int j = mid + 1;
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[j++];
else a[k] = aux[i++];
}
}
}