I was given an assignment to implement the following algorithm:
I am a little confused by reading the algorithm itself, I tried to follow the algorithm but, since I cannot understand it completely my code does not work. Can anyone, please, have a look at my code (this is the bit that I cannot understand what to fix):
public static void mergeSortNonRec(Comparable[] a) {
Comparable[] a1 = new Comparable[a.length];
Comparable[] b = new Comparable[a.length];
for (int i = 1; i < a.length; i *= 2) {
for (int j = 0; j < a.length; j += 2 * i) {
merge(a1, j, (Integer.min(j + i, a.length) - 1), a1, j + i, (Integer.min(j + 2 * i, a.length) - 1), b, 0);
}
}
for (int i = 0; i < a.length; i++) {
a[i] = a1[i];
}
}
This is my helper method that I have tested with my recursive mergeSort and I know it works:
private static void merge(Comparable[] a1, int left1, int right1, Comparable[] a2, int left2, int right2, Comparable[] a, int left) {
int i = left1;
int j = left2;
int k = left;
while (i <= right1 && j <= left2) {
int comp = a1[i].compareTo(a2[j]);
if (comp <= 0) {
a[k++] = a1[i++];
} else {
a[k++] = a2[j++];
}
}
while (i <= right1) {
a[k++] = a1[i++];
}
while (j <= right2) {
a[k++] = a2[j++];
}
}