I have to warn you right now. I’m a huge fan of fantasy novels. If that’s not your thing, your probably want to look elsewhere for your algorithm needs because it’s about to get magical around here. Needless to say, I needed a fun way to review my algorithms, so here inaugurates a series of magic-themed posts that should hopefully be a fun way to learn or relearn algorithms. This first week I will cover the bubble sort.

Bubble Sort

To start, let’s imagine you are stuck sorting cauldrons for Professor Snape after getting a detention in Potions class, or maybe you just want to help Winifred Sanderson sort her cauldron collection.

There are many ways you could do this, but since you’re a first year, you only know the bubble sort. The concept of the bubble sort is quite simple.

Let’s say Snape wants you to sort cauldrons by size. A bubble sort simple compares the first cauldron to the second, and if the first cauldron is bigger than the second we switch them. Then we do the same for the second cauldron and the third, witching them if necessary all the way on up to the last at which point we tell Snape we’re through and he gives us some other menial task to do until we can finally trudge back to the common room well after curfew.

Here is your basic incantation to bubble sort cauldrons:

We begin the spell by declaring the variable swapped . This variable must be declared at the top since we are using a do/while loop. I felt it was simpler to see the inter-workings of this algorithm by giving a distinction between the outer (do/while) and inner (for) loops.

Once swapped is declared we enter the for loop. First, we make the current variable equal to the list element at the index of i to store for letter. Then we declare the next variable equal to a ternary statement. Here’s the reason:

If we simply made next equal to list[i + 1] , there is the problem of when we reach the end of the array. list[i + 1] would then equal undefined , which helps no one. This is why we make next equal to either list[i + 1] or Number.POSITIVE_INFINITY . Positive infinity will aways be greater than any element in the array, which makes the loop end when we reach the end of the array because next < current will always be false by then.

We compare next and current to see if we need to swap or not. If we do, next becomes the value at list[i] and current becomes the value at list[i + 1] . The variable swapped is also set to true , which allows our outer loop to continue.

Once there are no variables to swap, swapped will be equal to false , we exit the inner loop and outer loop, and we return a list of nicely sorted cauldrons (I mean, numbers).

Conclusion

There you have it. We have successfully cast bubbilicus sorticus (Bubble sort), and now you have a shelf of sorted cauldrons even Snape would be proud of, that is at least until next Potions class.

Next week we’ll tackle the Merge Sort.