Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    
Take debugger and debug it. A hint: what a.length > i+1 expression means? –  zerkms Jan 25 at 20:45

1 Answer 1

up vote 0 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.