2

I'm testing out a selection sort but keep getting an infite loop.

Everything works fine when I have

while(arr.length > 3)

But when I make it any lower or change it to what it should be it causes an infinite loop in the code.

while(arr.length > 2)

Here is the rest of my code:

    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
  • Have you debugged it? Stepping through it and tracking the values of all your variables at each stage? Commented Mar 13, 2019 at 1:47

1 Answer 1

4

You need to reset smallest in each loop entries, otherwise once 11 is removed, other values will get compared against it and index never changes (3); and once index is greater than your array's length (at second iteration), your array is never spliced anymore.

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.