简体   繁体   中英

JS merge sort function runs out of memory

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);

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