I am working on writing my own recursive merge sort function from scratch in javascript, but any time I test it with any array of numbers I receive the following error: "TypeError: Cannot read property 'length' of undefined"
I have no idea why I am receiving this error since the only places I use the "length" property are on my argued arrray (within the mergeSort function) and on subarrays of this array (within the merge function). My merge function already works perfectly when tested on its own when given two sorted arrays of any length.
Here is my entire code:
function merge(arrayOne, arrayTwo){
let sorted = []
while(arrayOne.length > 0 && arrayTwo.length > 0){
if(arrayOne[0] < arrayTwo[0]){
sorted.push(arrayOne.shift());
} else{
sorted.push(arrayTwo.shift());
}
}
return sorted.concat(arrayOne).concat(arrayTwo);
}
function mergeSort(array){
let arrayLength = array.length;
let midpoint = arrayLength/2;
let firstHalf = array.slice(0, midpoint);
let secondHalf = array.slice(midpoint, arrayLength);
if(arrayLength < 2){
return array;
} else{
merge(mergeSort(firstHalf), mergeSort(secondHalf));
}
}
while(arrayOne.length > 0 && arrayTwo.length > 0){Your error, cannot read length of undefined, soarrayOneand/orarrayTwois undefined