[英]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.