i’m new to javascript and programming (3 months) and am trying to make a sorting algorithm visualizer like the ones you see on youtube. i had an issue where the for loops usually used were just way to quick to actually visualize so i just replaced the for loops with intervals. this has worked for bubble, insertion, quick and a few other sorting algorithms but i cant for the life of me get selection to work. for some reason when the swap(index1, index2) function is called minIndex and selectionI are always the same. i did the good old console.log and everything seems to work right until the swap function. its been 3 days of suffering and no progress please i need help or pointers
function selectionSort2() {
let selectionI = 0;
const selectionIloop = setInterval(() => {
if(selectionI > arr.length) {
clearInterval(selectionIloop);
}
let minIndex = selectionI;
let selectionJ = selectionI+1;
const selectionJloop = setInterval(() => {
if(selectionJ > arr.length) {
clearInterval(selectionJloop);
}
if(arr[selectionJ] < arr[minIndex]) {
minIndex = selectionJ;
}
selectionJ++;
}, 100);
swap(minIndex, selectionI);
selectionI++;
}, 100)
}
i was able to get it partially working by changing the selectionJloop to a for loop like this
function selectionSort() {
let selectionI = 0;
const selectionIloop = setInterval(() => {
if(selectionI > arr.length) {
clearInterval(selectionIloop);
}
let minIndex = selectionI;
for(let j = selectionI+1; j < arr.length; j++) {
if(arr[j] < arr[minIndex]) {
minIndex = j;
}
}
swap(minIndex, selectionI);
selectionI++;
}, 100)
}
but because the for loop doesnt have the 0.1s delay this version has an unfair advantage against the other algorithms whose for loops are restricted. also note that when i put a 0.1s delay inside the for loop as a setTimeout() that it resulted in the same issue as before.
at first i thought that it could be the delay time like the intervals cant have the same delay time but even after changing both of them many many times it just refuses to work.
and just incase heres my swap function:
function swap(index1, index2) {
temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
}
i tried changing the interval times to be different from eachother. i tried replacing the intervals with for loops with timeouts instead. i tried completely rewriting it in a different way. whats supposed to happen is minIndex should be the index of the smallest number in the arr whose index isnt less then i+1 but instead minIndex always becomes the same value as i
