为什么会造成无限循环?

问题描述 投票:2回答:1

我正在测试一个选择排序,但继续得到一个无限循环。

我有的时候一切都很好

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()
javascript arrays
1个回答
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)
© www.soinside.com 2019 - 2024. All rights reserved.