Bubble Sort with Swift

In this installment of SwiftyAlgos I am taking a look at Bubble Sort. Bubble Sort is largely considered to be one of the simplest of sorting algorithms. It works on the principal of iterative swapping, working programmatically through a collection and swapping value positions until ultimately reaching a point where all of the values are in the correct order.

It works like this…

simple put, we loop through each pair of indices, and compare the values, if the left is greater than the right we swap, if not we do nothing. Once we are able to loop through and have no swaps we can assume that the collection is sorted. Ideally this is best for small collections, even this simple example requires 3 total passes of 4 comparisons each; effective but not performant.

Let’s take a look at this in code…

looping through, comparing j with j-1 swap if needed and incrementing our index

and test it…

Check out the code here on GitHub

Closing thoughts…

Bubble sort is simple, which in some ways makes it rather elegant in my opinion. But elegant isn’t alway great, in the case of bubble sort it’s very time consuming, effective, but time consuming. This algorithm demonstrates a couple of great things, the first in fact being the reality that the dumbest possible solution is often a great place to start, especially when looking at the potential complexity of sorting collections. It also demonstrates how effective loops can be at tracking position for controlled outcomes. Thanks again to GeeksForGeeks for providing a great resource for learning CS concepts, and thanks also to a great new resource that I found on GitHub, The Swift Algorithm Club! As usual it’s important to remember that when you explain an idea you take the greatest steps towards mastery.

Until next time!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s