0

I'm trying to implement merge sort algorithm in JavaScript. But I'm getting a strange behavior when it comes to merging two sorted arrays.

When I pass those two arrays: [1,4, 5] and [3, 6, 7, 10] to the merge function, I always get this result: [ 1, 3, 4, 6, 7 ]. Strangely without the element 5 and 10 !

Here's my function:

function merge(a, b)
{
    var result = [],
        k = 0,
        i = 0,
        j = 0;

    while(a.length > i+1 && b.length > j+1){
        if(a[i] <= b[j]){
            result[k++] = a[i++];
        } else {
            result[k++] = b[j++];
        }
    }

    while(a.length > i+1) {
        result[k++] = a[i++];
    }

    while(b.length > j+1) {
        result[k++] = b[j++];
    }

    return result;
}

Any help would be appreciated.

Thanks.

1
  • Take debugger and debug it. A hint: what a.length > i+1 expression means? Commented Jan 25, 2015 at 20:45

1 Answer 1

1

Just replace i + 1 by i and j + 1 by j in all while loops' conditions and it will work properly. Currently the last elements of a and b are just ignored because their indices are a.length - 1 and b.length - 1, respectively.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.