簡體   English   中英

為什么會導致無限循環?

[英]why is while causing an infinite loop?

我正在測試選擇排序,但不斷收到infite循環。

當我有一切都很好

while(arr.length > 3)

但是,當我將其降低或更改為應有的水平時,則會在代碼中造成無限循環。

while(arr.length > 2)

這是我其余的代碼:

  let arr = [55,21,33,11,25] let newArr = []; let smallest = 999999999; let index; function selectionSort() { while(arr.length > 2) { //loops through the numbers array for(i = 0; i < arr.length; i ++) { // if the item is smaller, than pass it through if(arr[i] < smallest) { //change smallest to the arr[i] smallest = arr[i] index = i; } } //remove the smallest number from the arr arr.splice(index, 1) //push the smallest number to the new arr newArr.push(smallest) } } selectionSort() 

您需要在每個循環條目中重置smallest值,否則,一旦刪除11 ,其他值將與之進行比較,並且index永不變( 3 ); 一旦index大於數組的長度(第二次迭代),就不再拼接數組。

 let arr = [55, 21, 33, 11, 25] let newArr = []; let index; function selectionSort() { while (arr.length > 2) { let smallest = Infinity; //loops through the numbers array for (i = 0; i < arr.length; i++) { // if the item is smaller, than pass it through if (arr[i] < smallest) { //change smallest to the arr[i] smallest = arr[i] index = i; } } //remove the smallest number from the arr arr.splice(index, 1) //push the smallest number to the new arr newArr.push(smallest) } } selectionSort() console.log(newArr, arr) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM