为什么会导致无限循环?

时间:2019-03-13 01:41:18

标签: javascript arrays

我正在测试选择排序,但不断出现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()

1 个答案:

答案 0 :(得分:4)

您需要在每个循环条目中重置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)