Why is the console crashing in my browser, if I run this function in a variable in the browser console, it hangs or crashes, I can close the tab but the console just stops working.
let arr=[70,30,24,90,4];
function selectionSort(list){
let minIndex=0;
let minVal=0;
for(let i=0; list.length; i++){
minIndex=i;
minVal=list[i];
for(let j=i; j<list.length; j++){
if(list[i]< minVal){
minVal=list[i];
minIndex=j;
}
}
if(minVal<list[i]){
temp=list[i];
list[i]=list[minIndex];
list[minIndex]=temp;
}
}
return list;
}
let ar= selectionSort(arr);// causes console in chrome to stop working
Your code had a couple of issues, it's working like this
let arr = [70, 30, 24, 90, 4, 23];
function selectionSort(list) {
let minIndex = 0;
let minVal = 0;
for (let i = 0; i < list.length; i++) { // add "i < " to prevent infinite loop
minIndex = i;
minVal = list[i];
for (let j = i+1; j < list.length; j++) { // add "+1" (saves you a nano second)
if (list[j] < minVal) { // change to j (otherwise the sorting won't work)
minVal = list[j];
minIndex = j;
}
}
if (minVal < list[i]) {
let temp = list[i];
list[i] = list[minIndex];
list[minIndex] = temp;
}
}
}
selectionSort(arr)
console.log(arr)
Keep in mind that JavaScript is call is call by reference on arrays. So do not assign list to a new variable.