Understanding the Bubble Sort Algorithm, it is not the best and most efficient algorithm to sort data with but it does make for a great introduction to sorting algorithms because it is easy and quick to implement. This article is not going to be very long since the code is only a few lines and easy to understand but if you do want a visual, all the coding videos for this is down below. Bubble sort is quick and can effectively identify if data is already sorted, however, it offers no other significant advantages.
Understanding the Bubble Sort Algorithm
The algorithm works by iterating until the end of the data in a “linear” fashion. To get a better understanding, it will walk through the data comparing the data at the index n to the index of n + 1. If the index n is greater than n + 1, swap the two. Pretty easy, right? You can probably also see that it could take a long time to go through a lot of data. Let’s look at the pseudocode of how this algorithm works.
function bubbleSort(array A)
for i = 0 to A.length
for j = i + 1 to A.length
if A[i] > A[j]
swap A[i] with A[j]
You can see how easy it is to implement Bubble Sort. A little more than 4 lines of code if you replace the swap line with the lines of code to swap two places. The algorithm is quick and easy to stand up if you just need something quick to sort some data. As for why this algorithm gets slower with more data:
for i = 0 to A.length
for j = i + 1 to A.length
These two for loops both run to the length of A or size N in the worst case. Nested loops runtime will be n * n = n² = O(n²). That can become very large very fast. That is Bubble Sort. Hopefully you found this article helpful. If you would like to see if coded in different languages, check out the videos down below.