I am learning Java and algorithms at the same time. I implemented merge sort in this class.
public class Sorter {
private void merge(int [] numbers, int low, int mid, int high) {
// create a new array that will contain the merged integers
int[] arrIntMerged = new int[high - low + 1];
// set indices
int i = low, j = mid + 1, k = 0;
// add the lesser integer into merged array
while (i <= mid && j <= high) {
if (numbers[i] < numbers[j]) {
arrIntMerged[k] = numbers[i];
i++;
} else {
arrIntMerged[k] = numbers[j];
j++;
}
k++;
}
// add anything left in the left side of the array
while (i <= mid) {
arrIntMerged[k] = numbers[i];
i++;
k++;
}
// add anything left in the right side of the array
while (j <= high) {
arrIntMerged[k] = numbers[j];
j++;
k++;
}
// write this newly created array into the positions in the original array
for (int l = 0; l < arrIntMerged.length; l++) {
numbers[l + low] = arrIntMerged[l];
}
}
// recursive implementation
private void _mergeSort(int[] numbers, int low, int high) {
if (low == high)
return;
else {
// find midpoint while preventing overflow
int mid = low + (high - low) / 2;
// sort left and right side
_mergeSort(numbers, low, mid);
_mergeSort(numbers, mid + 1, high);
// merge both sides
merge(numbers, low, mid + 1, high);
}
}
// friendly interface to begin merge sort
public void mergeSort(int[] numbers) {
_mergeSort(numbers, 0, numbers.length - 1);
}
}
I then inspected this code in a scrapbook in Eclipse.
Sorter sorter = new Sorter();
int[] nums = {5, 6, 7, 8, 1, 2, 3, 4};
sorter.mergeSort(nums);
System.out.println(Arrays.toString(nums));
Unfortunately, standard output reads [2, 3, 4, 5, 6, 7, 8, 1], which is out of order. Why is my merge sort erring? I am pretty sure of my boundary conditions in _mergeSort, so I suspect my merge function is awry.
Your problem comes from the following assignment in
merge:midis already the index to the first number on the right side of the merge, this increment is making the rest of your merge logic start at the wrong array position.Because it looks like you are learning, I won’t spoil your experience by posting the actual code changes needed, but here a hint: check all the places where you compare things against the
midvalue.