我正在尝试在JS中进行合并排序,并且不知道我在哪里弄乱。我希望它返回[1,2,3,4]并返回[1,1,1,4]。
它需要改变哪些部分?
var array = [3,2,1,4]
function mergeSort(array) {
if (array.length === 1) {
return array
} else {
mid = Math.floor(array.length/2)
left = mergeSort(array.slice(0, mid))
right = mergeSort(array.slice(mid, array.length))
return merge(left, right)
}
}
function merge(left, right) {
var leftIndex = 0
var rightIndex = 0
var sorted = []
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] <= right[rightIndex]) {
sorted.push(left[leftIndex])
leftIndex += 1
} else {
sorted.push(right[rightIndex])
rightIndex += 1
}
}
if (leftIndex < left.length) {
sorted = sorted.concat(left.slice(leftIndex))
} else if (rightIndex < right.length) {
sorted = sorted.concat(right.slice(rightIndex))
}
return sorted
}
console.log(mergeSort(array))
答案 0 :(得分:2)
它工作正常(带有一些声明和分号)。
var array = [3, 2, 1, 4],
result = mergeSort(array);
function mergeSort(array) {
var mid, left, right;
if (array.length === 1) {
return array;
} else {
mid = Math.floor(array.length / 2);
left = mergeSort(array.slice(0, mid));
right = mergeSort(array.slice(mid, array.length));
return merge(left, right);
}
}
function merge(left, right) {
var leftIndex = 0,
rightIndex = 0,
sorted = [];
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] <= right[rightIndex]) {
sorted.push(left[leftIndex]);
leftIndex += 1;
} else {
sorted.push(right[rightIndex]);
rightIndex += 1;
}
}
if (leftIndex < left.length) {
sorted = sorted.concat(left.slice(leftIndex));
} else if (rightIndex < right.length) {
sorted = sorted.concat(right.slice(rightIndex));
}
return sorted;
}
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
答案 1 :(得分:2)
你有一个范围问题。您尚未声明left
,right
和mid
变量,因此它们被视为隐式全局变量并导致混乱。
修正:
function mergeSort(array) {
if (array.length === 1) {
return array
} else {
var mid = Math.floor(array.length/2)
var left = mergeSort(array.slice(0, mid))
var right = mergeSort(array.slice(mid, array.length))
return merge(left, right)
}
}