I was trying to improve the time of a typical merge-sort function using pop(). When I run it in Chrome, it crashes with memory errors. Obviously this means that it's looping without completing, but I can't tell why.
Here's the code:
function mergeSorted(a, b){
var c = [];
while(a.length && b.length){
var a1 = a.pop();
var b1 = b.pop();
var aIndex = parseInt((a.length) - 1);
var bIndex = parseInt((b.length) - 1);
while(b[bIndex] >= a[aIndex]) c.push(b1);
while(a[aIndex] >= b[bIndex]) c.push(a1);
}
return c;
}
var a = [1, 3, 5, 7, 7, 8, 8, 9, 9];
var b = [2, 4, 5, 6, 7, 8, 9];
mergeSorted(a, b);
Your last two while
loops should be if
conditions, since you don't change any of the while
loop conditions internally in the loop, so will loop indefinitely.
if(b[bIndex] >= a[aIndex]) c.push(b1);
if(a[aIndex] >= b[bIndex]) c.push(a1);