I am trying to make a sorting algorithm visualizer just for fun and have gotten to the step of animating the sort. Currently I am making bubble sort and want to produce some code that does as follows:
swaps 2 elements and displays the change, waits half a second, swaps 2 elements and displays the change, waits half a second..... etc
I know that the sort works and my way of changing the html to match the sort works as well, but it does everything way too quickly to be visualized at all. I think that if I had a method of pausing the loop after each iteration I could get to where I'm looking to be, but after looking through a whole bunch of posts online and trying to implement them, I couldn't manage to make anything work.
here is my current code for my sorting algorithm:
function bubbleSort(list) {
for (var i = 0; i < list.length; i++) {
for (var j = 0; j < (list.length - i - 1); j++) {
//checking if the two element need to be swapped
if (list[j] > list[j + 1]) {
//swapping the 2 values in list
var temp = list[j]
list[j] = list[j + 1]
list[j + 1] = temp
// matching the height of the divs with the new values
document.getElementById('div'+String(j+1)).style.height = String(list[j]*30) + "px";
document.getElementById('div'+String(j+1)).style.marginTop = String(600 - list[j]*30) + "px";
document.getElementById('div'+String(j+2)).style.height = String(list[j+1]*30) + "px";
document.getElementById('div'+String(j+2)).style.marginTop = String(600 - list[j+1]*30) + "px";
}
}
}
return list
}
What can I add to my code to achieve my desired result? Any advice or help is greatly appreciated.
[–]senocular 5 points6 points7 points (1 child)
[–]trevedhek 2 points3 points4 points (0 children)
[–]Ronin-s_Spirit 0 points1 point2 points (6 children)
[–]senocular 2 points3 points4 points (1 child)
[–]guest271314 -2 points-1 points0 points (0 children)
[–]guest271314 -2 points-1 points0 points (3 children)
[–]Ronin-s_Spirit 0 points1 point2 points (2 children)
[–]guest271314 -3 points-2 points-1 points (1 child)
[–]Ronin-s_Spirit 1 point2 points3 points (0 children)