gpt4 book ai didi

Javascript for 循环条件

转载 作者:行者123 更新时间:2023-12-01 03:33:49 24 4
gpt4 key购买 nike

enter image description here

我正在阅读可汗学院的算法类(class)。我在https://www.khanacademy.org/computing/computer-science/algorithms/insertion-sort/p/challenge-implement-insert .

After calling the insert function: * value and the elements that were previously in array[0] to array[rightIndex], should be sorted in ascending order and stored in the elements from array[0] to array[rightIndex+1]. In order to do this, the insert function will need to make room for value by moving items that are greater than value to the right. It should start at rightIndex, and stop when it finds an item that is less than or equal to value, or when it reaches the beginning of the array. Once the function has made room for value, it can write value to the array.

我的尝试是:

var insert = function(array, rightIndex, value) {

var i = rightIndex;
for( array[i]> key ; 0; i-- ) {

array[i + 1] = array[i];
}
array[i]= value;

};

var array = [3, 5, 7, 11, 13, 2, 9, 6];

insert(array, 4, 2);
println("Array after inserting 2: " + array);

他们明确表示他们想要在 for 循环中添加一个条件,但我不知道该怎么做。

最佳答案

 var insert = function(array, rightIndex, value) {
// for( initial_value; condition; change the value for next iteration)
// && - returns true only when both are true.
for(var j = rightIndex; j >= 0 && array[j] > value; j--) {
array[j + 1] = array[j];
}
array[j + 1] = value;

};

关于Javascript for 循环条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44398527/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com