IgnitiousNites
IgnitiousNites

Reputation: 165

Javascript array splice causing out of memory exception?

I am basically trying to sort an input of numbers on the fly by inserting the numbers to the correct position (not 100% sure but this should be insertion sort). My understanding is that to insert into an array in javascript you need to use the array splice method http://www.w3schools.com/jsref/jsref_splice.asp .

My code in attempt of achieving my goal is as below:

var N = parseInt(readline());
var powers = [0];
for (var i = 0; i < N; i++) {
    var pi = parseInt(readline());
    for(var j=i;j<powers.length; j++ ){
        if(powers[j]>pi){
            powers.splice(j,0,pi);
        }
        else if(j+1==powers.length){
            powers[j+1]=pi;
        }
    }
}

When I run this code I get an out of memory exception. I just want to understand is what I am doing wrong in the code above. If I am using the splice method wrong and it is the cause of the memory leak, what is actually happening under the hood? I know there are other ways I could do this sorting but I am particularly interested in doing an insertion sort with javascript arrays.

Upvotes: 0

Views: 579

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074989

In your else condition, you're adding to the array, making it one longer. That means when the loop next checks powers.length, it will be a higher number, which means you'll go into the loop body again, which means you'll add to the array again, which means you'll go back into the loop body again, which means...you see where this is going. :-)

Once you've added the number to the array (regardless of which branch), exit the loop (for instance, with break).


Side note: You won't be doing a proper insertion sort if you start j at i as you are currently. i is just counting how many entries the user said they were going to enter, it's not part of the sort. Consider: What if I enter 8 and then 4? If you start j at i, you'll skip over 8 and put 4 in the wrong place. j needs to start at 0.

Upvotes: 3

Related Questions