1
我想在JS中進行合併排序,但不明白我在哪搞亂了。我希望這返回[1,2,3,4],並返回[1,1,1,4]。JavaScript中的合併排序返回重複的元素
它的哪些部分需要更改?
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))
它是否應該只返回一個排序的數組像這樣'[1,2,3,4]',你爲什麼要「發明」這樣一個複雜的功能? – RomanPerekhrest