Code for merge sort.
//time: O(NlogN), space: O(N)
private void merge(int[] a, int lo, int mid, int hi) {
int[] aux = new int[a.length];
for(int k = 0; k < a.length; k++) {
aux[k] = a[k];
}
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[i++];
else a[k] = aux[j++];
}
}
private void sort(int[] a, int lo, int hi) {
int mid = lo + (hi - hi)/2;
if(lo >= hi) return;
sort(a, lo, mid);
sort(a, mid + 1, hi);
merge(a, lo, mid, hi);
}
public void sort(int[] a) {sort(a, 0, a.length - 1);}
//time: O(NlogN), space: O(N)
private void merge(int[] a, int lo, int mid, int hi) {
int[] aux = new int[a.length];
for(int k = 0; k < a.length; k++) {
aux[k] = a[k];
}
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[i++];
else a[k] = aux[j++];
}
}
private void sort(int[] a, int lo, int hi) {
int mid = lo + (hi - hi)/2;
if(lo >= hi) return;
sort(a, lo, mid);
sort(a, mid + 1, hi);
merge(a, lo, mid, hi);
}
public void sort(int[] a) {sort(a, 0, a.length - 1);}