繁体   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