I'm trying to create a non-recursive version of MergeSort but for some reason merge is keeping the code from running in its entirety.
Mergesort Code:
public void mergeSort(int[] input)
{
int n = input.length;
int size;
int l;
for (size = 1; size <= n-1; size = 2*size)
{
for (l = 0; l < n-1; l += 2*size)
{
int m = l + size -1;
int r = minimum(l + 2*size - 1, n-1);
merge(input, l, m, r);
}
}
}
Merge code:
public static void merge(int[] numbers, int low, int middle, int high)
{
// Copy both parts into the helper array
int helper[];
helper = new int[numbers.length];
for (int i = low; i <= high; i++) {
helper[i] = numbers[i];
}
int i = low;
int j = middle + 1;
int k = low;
// Copy the smallest values from either the left or the right side back
// to the original array
while (i <= middle && j <= high) {
if (helper[i] <= helper[j]) {
numbers[k] = helper[i];
i++;
} else {
numbers[k] = helper[j];
j++;
}
k++;
}
// Copy the rest of the left side of the array into the target array
while (i <= middle) {
numbers[k] = helper[i];
k++;
i++;
}
}
This is how I fill up the input array (which is of size 100):
public static int fillArray()
{
Random r = new Random();
int rand = r.nextInt();
return rand;
}
//followed by these lines of code in the main method:
int[] arr;
arr = new int[100];
for(int i =0; i<arr.length; i++)
{
arr[i] = fillArray();
}
The exception is with numbers[k] = helper[i]
in merge()
.
I know that the contents of the input array are fine because I print out the contents of the array before I perform MergeSort on it. Does anyone know what the problem is?