Here is an implementation of merge for mergesort, in Java that works:
void merge(int[] numbers, int low, int mid, int high) {
int helper[] = new int[numbers.length];
for (int i = low; i <= high; i++) {
helper[i] = numbers[i];
}
int lowone = low;
int lowtwo = mid + 1;
int count = low;
while (lowone <= mid || lowtwo <= high) {
if (lowone <= mid && lowtwo <= high) {
if (helper[lowone] <= helper[lowtwo]) {
numbers[count] = helper[lowone];
lowone++;
} else {
numbers[count] = helper[lowtwo];
lowtwo++;
}
}
else if (lowone <= mid) {
numbers[count] = helper[lowone];
lowone++;
}
else {
numbers[count] = helper[lowtwo];
lowtwo++;
}
count++;
}
}
//msort algorithm in case it's relevant
void msort(int[] arr, int low, int high) {
if (low < high) {
int mid = (low + high)/2;
msort(arr, low, mid);
msort(arr, mid + 1, high);
merge(arr, low, mid, high);
}
}
In my first attempt at merge I was trying to have the second half of the array contain the midpoint index instead of having it in the first half. Here is the relavent code (note there are only 4 changes from above):
int lowtwo = mid;
while (lowone < mid || lowtwo <= high) {
if (lowone < mid && lowtwo <= high) {
if (helper[lowone] <= helper[lowtwo]) {
numbers[count] = helper[lowone];
lowone++;
} else {
numbers[count] = helper[lowtwo];
lowtwo++;
}
}
else if (lowone < mid) {
numbers[count] = helper[lowone];
lowone++;
}
else {
numbers[count] = helper[lowtwo];
lowtwo++;
}
The modified version used with msort (above) does not correctly sort the list. Maybe it's obvious, but I can't seem to figure out why it doesn't work.