我正在尝试使用 HTML 和 Javascript 直观地实现合并排序算法。我的合并排序实现的输出按计划工作,但我不断在终端窗口中收到错误。
//Merge Sort Algorithm Implementation
//Function for dividing array into two sub problems
divide = (array) => {
if (array.length < 2) {
return array
}
const mid = Math.floor(array.length / 2)
const smallOne = array.slice(0, mid)
const smallTwo = array.slice(mid)
return sort(divide(smallOne), divide(smallTwo))
}
//Function for sorting array
sort = (smallOne, smallTwo) => {
const sorted = []
while (smallOne.length && smallTwo.length) {
if (smallOne[0] <= smallTwo[0]) {
sorted.push(smallOne.shift())
} else {
sorted.push(smallTwo.shift())
}
}
const output = [...sorted, ...smallOne, ...smallTwo]
console.log(output)
return output
}
//Functiom for merge sort
mergeSort = (array) => {
return sort(divide(array))
}
这是我在控制台中出现的错误的图片
最佳答案
您收到错误是因为 smallTwo
在 sort
函数中是 undefined
。
完整的错误消息是:
while (smallOne.length && smallTwo.length) {
^
TypeError: Cannot read property 'length' of undefined
关于javascript - 我的程序不断收到此错误 : VM178 SortLib. js:71 Uncaught TypeError: 无法读取未定义的属性 'length',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60264574/