public class MergeSort {
public static void sort(int[] array, int lo, int hi) {
if (hi <= lo) {
return;
}
int mid = lo + (hi - lo) / 2;
sort(array, lo, mid);
sort(array, mid + 1, hi);
mergesort(array, lo, mid, hi);
}
private static void mergesort(int[] array, int lo, int mid, int hi) {
int[] aux = new int[array.length];
for (int i = 0; i < array.length; i++) {
aux[i] = array[i];
}
int i = lo;
int j = mid + 1;
for (int k = lo; k <= hi; k++) {
if (i > mid) {
array[k] = aux[j++];
} else if (j > hi) {
array[k] = aux[i++];
} else if (aux[i] > aux[j]) {
array[k] = aux[j++];
} else {
array[k] = aux[i++];
}
}
}
public static void main(String[] args) {
int[] a = { 3, 1, 5, 1, 8, 23, 55, 54, 10, 12, 5 };
MergeSort.sort(a, 0, a.length - 1);
show(a);
}
private static void show(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}
It took me a whole day and a half to understand the code but I did a quick test and it worked. One thing I am concerned with is that the coursera class I am taking does it differently, instead of creating aux in mergesort they create aux in a helper class and pass around BOTH arrays in the sort and mergesort method. It looked like this:
private static void sort(Comparable[] a, Comparable[] 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);
}
/**
* Rearranges the array in ascending order, using the natural order.
* @param a the array to be sorted
*/
public static void sort(Comparable[] a) {
Comparable[] aux = new Comparable[a.length];
sort(a, aux, 0, a.length-1);
assert isSorted(a);
}
and when it got to the merge sort method it finally copies the aux array, what is the point of this route? It looks like it just takes more code.