简体   繁体   English

汗学院:JavaScript循环时间过长

[英]Khan academy: JavaScript loop taking too long

在此处输入图片说明

I'm reading through the khan academy course on algorithms. 我正在阅读可汗学院算法课程。 I'm at https://www.khanacademy.org/computing/computer-science/algorithms/insertion-sort/p/challenge-implement-insertion-sort . 我在https://www.khanacademy.org/computing/computer-science/algorithms/insertion-sort/p/challenge-implement-insertion-sort So far I have: 到目前为止,我有:

var insert = function(array, rightIndex, value) {
for(var j = rightIndex;
    j >= 0 && array[j] > value;
    j--) {
    array[j + 1] = array[j];
}   
array[j + 1] = value; 
};

var insertionSort = function(array) {

for(var i= 1;  i < array.length ; i++ ) {
    insert(array, i ,array[i+1] );
}

};

var array = [22, 11, 99, 88, 9, 7, 42];
insertionSort(array);

You can see the line of code in the screenshot which appears to be the problem , but it looks fine to me. 您可以在屏幕截图中看到似乎是问题所在的代码行,但对我来说看起来不错。 What am I doing wrong? 我究竟做错了什么?

You're starting rightIndex off at i and moving the value array[i + 1] , but i reaches array.length and insert starts by setting the element at rightIndex + 1 . 您从i处开始rightIndex并移动了值array[i + 1] ,但是i到达array.length并通过将元素设置为rightIndex + 1开始insert This will cause the array to grow. 这将导致阵列增长。

Move the current element and start at the previous index instead: 移动当前元素并从上一个索引开始:

for (var i = 1; i < array.length; i++) {
    insert(array, i - 1,array[i]);
}

One way to catch this when debugging is to seal your array so it can't grow: 调试时捕获此错误的一种方法是密封数组以使其无法增长:

var array = Object.seal([22, 11, 99, 88, 9, 7, 42]);

This only works in strict mode , though. 不过,这仅适用于严格模式 If you're in sloppy mode, it will just hide mistakes. 如果您处于草率模式,它将只会隐藏错误。

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

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