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.
a.length > i+1expression means?