Bubble Sort — Concept and Visualization

Nash
2 min readOct 1, 2022

--

Bubble Sort is one of the simplest sorting algorithms that works by repeatedly swapping the adjacent elements if they are in the wrong order.

Pseudocode

For i = 0 to (i < N)
For j = 0 to (j < N - i - 1)
a = arr[j]
b = arr[j+1]
if(a>b) swap(a,b)

The first loop indicates the round of finding the nth biggest element in the array. For example, i= 0 means we are currently finding the 1st maximum element in the array. at i=1 is the 2nd maximum element in the array and so on…

The second loop is where the comparison takes place, there will be a swapping process here, and in the end, the one that is the biggest will be swapped to the end of the array.

Notice that in the second loop, we iterate all the elements up to before the index N — i — 1 which is basically nothing but excluding the elements that are already sorted in the previous rounds.

Time Complexity

As we can guess from the pseudocode, when there is a nested loop, the time complexity would be O(n²), thus making this algorithm not efficient in a large dataset.

So slow!

That’s it!

Thanks for reading and I hope you enjoy my article. Any feedback or mistakes correction will be appreciated.

Wanna play around?

Want to adjust the speed to be slower? Or maybe increase the array size up to 1500 items? Then feel free to go ahead and try it on my website at sortlab.click

sortlab.click

--

--