I’m trying to draw visual representation of sorting algorithms. Bubble Sort is working fine, but Selection Sort don’t care about how much time I put in the setInterval timer, he runs on the same speed no matter what (until I manually put sleep, but that’s not the solution)
Can you guys help me understand what’s wrong here? It’s strange, because bubble sort works very good.
Bubble Sort
function bubbleSort(X, Y, LastX, LastY, no_loops, no_steps, time) {
var i, j;
var len = LastY.length;
var isSwapped = false;
for (i = 0; i < len; i++) {
var intervalId = setInterval(function() {
ctx.clearRect(0, 0, canvasElement.width, canvasElement.height);
isSwapped = false;
for (j = 0; j < len; j++) {
if (LastY[j] > LastY[j + 1]) {
var temp = LastY[j]
LastY[j] = LastY[j + 1];
no_steps = no_steps + 1;
LastY[j + 1] = temp;
no_steps = no_steps + 1;
isSwapped = true;
}
}
drawArray(X, Y, LastX, LastY);
no_loops = no_loops + 1;
no_steps = no_steps + 1;
document.getElementById("p1").innerHTML = no_loops;
document.getElementById("p2").innerHTML = no_steps;
if (isArraySorted(LastY) == true) {
clearInterval(intervalId);
}
}, time);
if (!isSwapped) {
break;
}
}
}
Selection Sort
function selectionSort(X, Y, LastX, LastY, no_loops, no_steps, time) {
let n = LastY.length;
for (let i = 0; i < n; i++) {
var intervalId = setInterval(function() {
ctx.clearRect(0, 0, canvasElement.width, canvasElement.height);
let min = i;
for (let j = i + 1; j < n; j++) {
if (LastY[j] < LastY[min]) {
min = j;
}
no_steps = no_steps + 1;
}
if (min != i)
let tmp = LastY[i];
LastY[i] = LastY[min];
LastY[min] = tmp;
no_steps = no_steps + 1;
}
drawArray(X, Y, LastX, LastY);
//sleep(time);
console.log(time) no_loops = no_loops + 1; no_steps = no_steps + 1;
if (isArraySorted(LastY) == true) {
return;
}
console.log(i); document.getElementById("p1").innerHTML = no_loops; document.getElementById("p2").innerHTML = no_steps;
if (isArraySorted(LastY) == true) {
clearInterval(intervalId);
}
},
time);
}
}
I was trying parsing code block in interval to external function, changing placement of setInterval, but i can’t get it to draw properly.
2
Answers
Sorry guys, i did not gave you enough info. @RAllen, you are a genious, thank you. It's working like a charm now. I need just google what "*" means before function.
@Mr. Polywhirl @Barmar
Full code below
With your approach, you will have an increasing number of issues with the more complex sorting algorithms.
Why not just use yield to return control to your main function to draw the current state on every step of sorting?
And with the Selection sort