Visualizing Bubble Sort

Ayushman Gupta
Nerd For Tech
Published in
5 min readApr 9, 2021

--

I’m pretty sure that you’ve heard about the bubble sort algorithm before. It is probably the simplest and weakest sorting algorithm. Honestly, I had never found algorithms interesting, but I was fortunate enough to stumble upon this article by Mike Bostock. In this article, he explained how different algorithms can be visualized. He stated the point that you don’t need a data set to visualize it. You can use the elegance of maths and logic to create stunning visuals.

I searched through the internet and I found wonderful visual arts created by using simple algorithms. So I decided to unpack my paintbrush as start visualizing different algorithms.

Since I’ve never tried visualizing algorithms before, I wanted to start with something simple yet graceful and the only algorithm that I could remember from my college days was the bubble sort algorithm.

Bubble Sort Algorithm

There are numerous articles out there that can explain this algorithm better than I. But I’ll try to give a brief overview, so you don’t have to take the extra pain of clicking on the new tab.

So this is how bubble sort works. You take the first element compare it with the immediately adjacent one and switch them it meets your sorting criteria.

Move to the next element and again compare it to the immediate next element. Repeat this process till you reach the end of your element. By this time you should have the largest or smallest element (based on your criteria) on the right-most side.

The next time you loop through your elements you don’t need to consider the last element. This means we will be looping through the elements one less time than the previous one.

Now that the boring part is covered, we can visualize data. By data, I mean the random values that I’ll generate.

Sorting random heights

I’m using P5.js here to visualize this algorithm. It’s a very powerful and yet simple JavaScript library to handle 2D and 3D processing.

Let’s take a look at the code. Here the two functions at global scope — setup and draw are provided by P5.js. The setup function runs only a single time at the start of the execution. As the name applies, this function can be used to set up the initial state of our processing. The draw function is called on every frame. So here we actually draw on the canvas.

We have three global variables — array, i and sortedArr. The array is where I’m storing the elements to filter them later on. i is the counter which tracks the loop progress and finally sortedArr an optional variable that I’m using to change the colour of sorted elements.

setup() — The first line inside the setup function is createCanvas() which takes two arguments — width and height of the canvas. On the next line —

array = new Array(width).fill().map(() => floor(random() * height));

I’m creating a new array with elements number equals to the width of the user’s browser and filling them with random values from the range of 0 to the height of the browser.

draw() — Inside the draw functions, after setting the background colour and I’m having an if check which will run the bubble sort algorithm.

if (i > 0) {
for (let j = 0; j < i; j++) {
if (array[j] > array[j + 1]) {
const temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
sortedArr[i] = true;
i--;
}

Here an if condition is required to make sure it stops the sorting after all the elements are sorted and not continue with each subsequent draw method. Inside the loop, I’m checking the two adjacent elements and switching them based on the sorting criteria [bubble sort].

for (let i in array) {
stroke(42, 178, 138);
line(i, height, i, height - array[i]);
}
if (sortedArr[i]) {
stroke(24, 98, 76);
line(i, height, i, height - array[i]);
}
}

In this final piece of code, I’m drawing the lines, based on the height of the element.

Sorting random grayscale

Instead of sorting height’s on lines, let’s sort grayscale. A grayscale value is 2⁸ bits. Meaning it can hold value from 0 to 255. 0 being the absolute black and 255 being absolute white.

array = new Array(width).fill().map(() => floor(random() * 255));

Here I’m generating random value from 0–255.

for (let i in array) {
fill(array[i]);
rect(i, 0, 2, height);
}

This time I’m creating rectangles of width 2 pixels and height of the user’s browser. Filling them with randomly generated grayscale value in my array.

I couldn’t upload the GIF for grayscale sorting. Click here for a preview.

Sorting random circles radii

If we are sorting circles based on their radius and drawing them from a single point of origin, then it’s useless to sort them because you will just change the circle’s position and since all circles’ centre is the same, it won’t change the visual appearance. So here I changing the colour of sorted circles. It came out pretty good visually in the end, even though it doesn’t make much sense sorting them like this.

array = new Array(noOfCircles)
.fill()
.map(() => floor(random(1, height - 50)));

This time I’m filling the random values from a range between 1 to height — 50 to make sure the circles are not overflowed from the browser’s view.

Conclusion

Visualizing algorithms is quite fun and I’ll be visualizing some advanced algorithms in the future. You can use P5.js or unity for visualizing these algorithms. If you find these sort of things fun, read the article that I mentioned in the starting. I suggest you check this youtube channel (I don’t know anything about this guy besides that he creates wonderful simulations in unity) as well. You can also visit the GitHub repo for the complete code. See you next time with some other visualization.

--

--