Okay, I should start off by apologizing about the misleading nature of the title of this article. Bubble sort is not one of my favorite sorting algorithms and, therefore, does not make me feel particularly bubbly. That being said, I feel that bubble sort is a great if you are just getting started with sorting algorithms or just algorithms in general, so let’s get to it!
Bubble sort works by making the larger values of an array sort of ‘bubble’ to the top. We start with an array, [21, 23, 42, 12, 40], and we compare each pair of numbers as we iterate through it. As we compare we check to see if the first number in the pair is larger than the second. If it is larger, we swap the two numbers! The photos below shows the first swap that will happen between 42 and 12.
This of course happens again with 42 and 40 before we start the loop again…
This process continues until all of our largest numbers have ‘bubbled’ to the top and the array is sorted!
Now code it!
First we build our swap function for when we find one number that is larger than the other in the pair. This function takes in three arguments: the array and the two indexes of the elements we would like to swap.
Then, using swap() we build out our bubbleSort() function which takes in our unsorted array and returns it to us sorted!
The time complexity of Bubble Sort is not great, sitting pretty at O(n²) time. This is due to the nested loop nature of the function. For this reason, bubble sort is not so widely used. I highly recommend you check out my blog on Merge Sort here and check back later for more blogs on other sorting algorithms!