这是用于合并排序的合并实现,在 Java 中有效:
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);
}
}
在我第一次尝试合并时,我试图让数组的后半部分包含中点索引,而不是在前半部分包含它。这是相关代码(请注意,上面只有 4 处更改):
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++;
}
与 msort(上图)一起使用的修改版本无法正确排序列表。也许这很明显,但我似乎无法弄清楚为什么它不起作用。