почему while вызывает бесконечный цикл?

#javascript #arrays

#javascript #массивы

Вопрос:

Я тестирую сортировку по выбору, но продолжаю получать бесконечный цикл.

Все работает нормально, когда у меня

 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. Вы его отладили? Пошаговое выполнение и отслеживание значений всех ваших переменных на каждом этапе?

Ответ №1:

Вам нужно сбросить 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)