简体   繁体   中英

Passed into the function array is undefined

I want to enhance merge sort algorithm so that it sorts two arrays and removes duplicates. I've came up with the following code:

function mergeSortEnhanced(arr, arr2)
{
    while(arr2.length)
     {
        arr.push(arr2.shift());
     }
    if (arr.length < 2)
        return arr;

    var middle = parseInt(arr.length / 2);
    var left   = arr.slice(0, middle);
    var right  = arr.slice(middle, arr.length);

    return merge(mergeSortEnhanced(left), mergeSortEnhanced(right));
}

function merge(left, right)
{
    var result = [];

    while (left.length && right.length) {
        if (left[0] < right[0])
        {
            result.push(left.shift());
        } 
        else if(left[0] > right[0])
        {
            result.push(right.shift());
        }
        else
        {
            result.push(left.shift());
            right.shift()
        }
    }

    while (left.length)
        result.push(left.shift());

    while (right.length)
        result.push(right.shift());

    return result;
}
var a = [1, 2 , 2 , 1];
var b = [1, 1, 6 ,8];
console.log(mergeSortEnhanced(a, b).join());

The problem is that i encounter an error in the fourth line

while(arr2.length)

which states that compiler cannot compute length of undefined. i don't understand why the second array is undefined inside the function and how do I fix it

The problem is with the

return merge(mergeSortEnhanced(left), mergeSortEnhanced(right));

you pass only first parameter in function here, thus second one is undefined. maybe you wanted to do

    return merge(left, right);

BTW just as an advice - be extremely careful with recursion

Add check before while. Update your code as

if (arr2){
    while(arr2.length)
     {
        arr.push(arr2.shift());
     }
}

The shift() method removes the first item of an array, and returns that item. So after 4 iterations your arr2 becomes undefined.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM