Reputation: 1513
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()
Upvotes: 2
Views: 93
Reputation: 136755
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)
Upvotes: 4