我正在同时学习 Java 和算法。我在这个类中实现了归并排序。
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);
}
}
然后我在 Eclipse 的剪贴簿中检查了这段代码。
Sorter sorter = new Sorter();
int[] nums = {5, 6, 7, 8, 1, 2, 3, 4};
sorter.mergeSort(nums);
System.out.println(Arrays.toString(nums));
不幸的是,标准输出读取[2, 3, 4, 5, 6, 7, 8, 1]
,这是乱序的。为什么我的归并排序出错了?我很确定我的边界条件_mergeSort
,所以我怀疑我的merge
函数有问题。