I'm working on developing my own basic sorting algorithm visualizer. When I try to swap two integers in an array, I run into a problem. I need the swap function to switch the visible lines on the graph as part of the procedure.
This has previously been developed in Python, and I'm attempting to redo it in Javascript.
My problem is that when I swap two values, the previous lines are not cleared and are just drawn over by the new lines. After attempting to shuffle the array, this is what it looks like:
The array was first sorted from least to greatest, then shuffled.
The code is as follows:
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);
}
}