Visualizing Bubble Sort with p5.js

Click on the canvas to refresh the animation

I wanted to make a visualization for an algorithmic problem involving backtracking when I noticed the solution was remarkably similar to Bubble Sort. As it is often very helpful to work on a simpler, related problem than tackling a complex problem straight away, I decided to make a Bubble Sort Visualizer as a step on the way to solving the original problem (which was to find the minimum value that can be formed by swapping k digits in a positive integer). You can read more about Bubble Sort here.

I did a bit of digging around to find if there were any tools which could help with this project, and I stumbled upon p5.js, which a fantastic tool based on JaveScript.

p5.js is a JavaScript library for creative coding, with a focus on making coding accessible and inclusive for artists, designers, educators, beginners, and anyone else! p5.js is free and open-source because we believe software, and the tools to learn it, should be accessible to everyone.

With a little bit of work I was able to come up with the visualization above for Bubble Sort using remarkably few lines of code.

Code Listing for Bubble Sort Visualization with p5.js

The code listing for this visualization is below, with comments to help you understand how it works.

One thing that caught me out getting this to work was variable scope. There were a few places where I initially used the JS let keyword when I wanted to access a global variable (p5.js appears to make a lot of use of these…). Using let meant new local versions of variables were created which did not contain the values I expected. Just a heads up, that is something to look out for when working with p5.js.

The HTML you will need is:

Along with the p5.js source from a CDN. E.g.

If you want to get p5.js you can download it or get a link to the CDN version here.

I hope you find something of value in this article, whether it’s the Bubble Sort visualization itself or maybe some inspiration to check out p5.js for yourself.

Happy Computiung.

 Take your Python skills to the next level!

with our free email course on object oriented programming with Python