I am trying to implement the Merge Sort Algorithm visually using HTML and Javascript. My output for the Merge Sort Implementation works as planned, but I keep on getting an error in my terminal window.
//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))
}
Here's a picture of my error in the console
You are getting the error because that smallTwo
is undefined
inside the sort
function.
The Full error message is:
while (smallOne.length && smallTwo.length) {
^
TypeError: Cannot read property 'length' of undefined
Second parameter is missing
mergeSort = (array) => { return sort(divide(array), ????) }
I think you can just call divide from mergeSort , As sort is expecting two variables and the sort call in mergeSort is called finally with already sorted output with a single parameter ..
mergeSort = (array) => { return divide(array); }
you are calling the sort one more time after the array is being sorted
and the second array which is smallTwo become undefined
you can check if its undefined before your while iterator
if (!smallTwo) {
smallTwo = []
}
that could solve you problem
or just send an empty array in your first call like this
mergeSort = (array) => {
return sort(divide(array), [])
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.