I'm trying to create my own basic sorting algorithm visualizer. I'm running in to an issue when trying to swap two numbers in an array. As part of the process, I need the swap function to also swap the visual lines on the graph.
I've already written this in Python and I'm trying to rewrite it in javascript. This is a gif of it working as intended in Python: https://i.imgur.com/IVWuZ2o.gifv
My issue is that when I want to swap two values, the original lines are not cleared, and are instead just drawn over with the new lines. This is what it ends up looking like after attempting to shuffle the array:
The array was initially sorted least to greatest, then shuffled
Here's the code:
function eraseLine(a, i) {
ctx.clearRect(i * lineWidth, height - a[i], lineWidth, a[i]);
}
function swap(a, i, j) {
// clear the lines already there
lineWidth = width / a.length;
ctx.lineWidth = lineWidth;
eraseLine(a, i);
eraseLine(a, j);
// actually swap the values
var temp = a[i];
a[i] = a[j];
a[j] = temp;
// redraw the new lines
ctx.strokeStyle = "#FFFFFF";
ctx.moveTo(i * lineWidth + lineWidth / 2, height);
ctx.lineTo(i * lineWidth + lineWidth / 2, height - a[i]);
ctx.stroke();
ctx.moveTo(j * lineWidth + lineWidth / 2, height);
ctx.lineTo(j * lineWidth + lineWidth / 2, height - a[j]);
ctx.stroke();
}
async function eraseLines(a, start, end) {
for(var i = start; i < end; i++) {
eraseLine(a, i);
await sleep(50);
}
}
async function shuffle(a) {
for(var i = a.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
swap(a, i, j);
await sleep(50);
}
}