简体   繁体   English

Javascript数组拼接导致内存不足异常?

[英]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). 我基本上是试图通过将数字插入正确的位置(不是100%肯定,但这应该是插入排序)来动态地对数字输入进行排序。 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 . 我的理解是,要使用JavaScript插入数组,您需要使用数组拼接方法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? 如果我使用错误的splice方法,并且是导致内存泄漏的原因,那么实际上是在幕后发生了什么? I know there are other ways I could do this sorting but I am particularly interested in doing an insertion sort with javascript arrays. 我知道还有其他方法可以进行这种排序,但是我对使用javascript数组进行插入排序特别感兴趣。

In your else condition, you're adding to the array, making it one longer. 在您的else条件下,您要添加到数组,使其更长。 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. 这意味着当循环接下来检查powers.length ,它将是一个更大的数字,这意味着您将再次进入循环主体,这意味着您将再次添加到数组中,这意味着您将返回到再次循环身体,这意味着...您可以看到前进的方向。 :-) :-)

Once you've added the number to the array (regardless of which branch), exit the loop (for instance, with break ). 将数字添加到数组后(无论哪个分支),退出循环(例如,使用break )。


Side note: You won't be doing a proper insertion sort if you start j at i as you are currently. 旁注:如果像现在一样在i处开始j ,则不会进行正确的插入排序。 i is just counting how many entries the user said they were going to enter, it's not part of the sort. i只是在计算用户说要输入的条目数,这不是排序的一部分。 Consider: What if I enter 8 and then 4? 考虑:如果我输入8,然后输入4,该怎么办? If you start j at i , you'll skip over 8 and put 4 in the wrong place. 如果从i开始j ,则将跳过8并将4放在错误的位置。 j needs to start at 0. j需要从0开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM