繁体   English   中英

插入对我编码的内容进行排序,无法正确获得结果

[英]Insertion Sort what i code, doesn't get result correctly

let Array = [31, 41, 59, 26, 41, 58]
let len = Array.length;

for (let j=1; j < len; j++) {
    let key = Array[j]
    console.log(key)
    let i = j-1
    while(i > 0 && Array[i] > key) {
        Array[i+1] = Array[i]
        i = i-1
    }
    Array[i+1] = key
}

console.log(Array)

Output:[31、26、41、41、58、59]

为什么结果不正确? 我不知道这里有什么问题。 谁能帮我?

您不应使用JavaScript的内置对象的名称来命名变量。

[1]您的变量Array实际上覆盖了 JavaScript 的Array JavaScript 要解决此问题,您只需使用不会覆盖内置对象的名称来命名变量。

此外,遍历子数组的while循环应考虑索引0 ,因此循环声明应为while (i >= 0 && arr[i] > key)

这是一个带有一些有用解释的工作演示:

 /** "Array" is renamed into "arr" in order to prevent overriding built-in Array object */ let arr = [31, 41, 59, 26, 41, 58], len = arr.length; /** loop through the entire array */ for (let j = 1; j < len; j++) { /** cache the current elemnt in a variable so it can be used along the way */ const current = arr[j]; /** the max index of the sub array */ let i = j - 1; /** * loop over the sub array, account for index "0" as well so we get proper permutations. * Also decrement "i" by a value of "1". */ while (i >= 0 && arr[i] > current) arr[i + 1] = arr[i--]; arr[i + 1] = current; } /** print the result */ console.log(arr)

[1] :对于每个人来说,对于 OP 的代码,我的答案的第二个短语可能不是很正确
事实上,内置Array object 不会被覆盖。 这似乎具有误导性,但我这样说是为了建议不要使用内置对象名称命名变量
无论如何,如果这里的let关键字let Array = [...]被意外省略了,那将是另一个故事,它最终会覆盖Array内置的 object,这确实不推荐。
我刚刚测试过,即使使用let内置Array object 被覆盖!

暂无
暂无

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

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