Bubble Sort Cutaway
Bubble sort at your pace
What is bubble sort?
Bubble sort is a relatively easy to understand and easy to implement algorithm. It was one of the earliest ones to be discovered. It has an average and worst- case complexity of \(O(n^2)\) and a space complexity of \(O(n)\).
The algorithm itself is intuitive and involves swapping elements, that are not in the correct order, by repeatedly traversing the array until all the elements are in the correct order i.e., the array has been sorted.
Owing to its high complexity, it is rarely used in practice. However, it is interesting to observe it at work. A basic bubble sort implementation is shown below:
|
|
Our cutaway implementation
Our implementation adds some features to the code that helps us observe the working of the algorithm as it goes about its business. The highlighted lines in the code below help us with the ‘animation’. You will also note the early exit from the loop, as soon as one traversal happens without any swaps, indicating that the array is already sorted.
As the run progresses, pairs of numbers are highlighted in cyan color if they are already in order and in yellow if they need to be swapped. The array then updates to show the post swap status if applicable. You can tweak the highlighting characters if the colors do not show up on your terminal. The
sleep
amount on line 53 can also be suitably changed.
|
|
Playing around with the code
Here are some things you can try out to understand the algorithm better.
- Try sorting an array with a large number like 99 followed by other smaller numbers and watch the large number drift to the end of the array.
- Try sorting an already sorted array. What do you observe? Would you get the
same behaviour without the
swap
flag? - In the comparison statement on line 49, try changing the
>
to<
. What happens to array sorting behaviour?