我在Java脚本和Golang中有一个合并排序实现.它在Golang中运行正常,然而,在Java中,它似乎总是被关闭1.我没有发现任何明显的错误.如果能有任何关于它失败的原因的见解,我将不胜感激
我试过了:
- 将
for
迭代更改为从leftStart
开始 - 将中间元素从
Math.floor
更改为Math.ceil
和Math.round
- 从
start
合并到middle-1
,从middle
合并到end
function mergeSort(arr) {
merge(arr, 0, arr.length - 1, []);
}
function merge(arr, start, end, temp) {
if (start >= end) {
return;
}
const middle = Math.floor((start + end) / 2);
merge(arr, start, middle, temp);
merge(arr, middle + 1, end, temp);
mergeHalves(arr, start, end, temp);
}
function mergeHalves(arr, leftStart, rightEnd, temp) {
const leftEnd = Math.floor((leftStart + rightEnd) / 2);
const rightStart = leftEnd + 1;
const size = rightEnd - leftStart + 1;
let left = leftStart;
let right = rightStart;
let index = left;
while (left <= leftEnd && right <= rightEnd) {
if (arr[left] <= arr[right]) {
temp[index] = arr[left];
left++;
} else {
temp[index] = arr[right];
right++;
}
index++;
}
while (left <= leftEnd) {
temp[index] = arr[left];
index++;
left++;
}
while (right <= rightEnd) {
temp[index] = arr[right];
index++;
right++;
}
for (let i = 0; i < size; i++) {
arr[i] = temp[i];
}
}
测试用例:
const arr = [2, 1, 3, 5, 6, 2, 7];
mergeSort(arr);
//coming back as [1, 2, 3, 5, 6, 2, 7]
expect(arr).toEqual([1, 2, 2, 3, 5, 6, 7]);