Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order. It examines all pairs of adjacent elements, swapping them when they are out of order.

Bubble Sort
Algorithm :
for i in 0 .. n-2
for j in i .. n-1
if (a[j] > a[j+1]) swap(a[j], a[j+1])
We need to stop when we make a pass that doesn’t swap anything.
for i in 0 .. n-2
swapped := false
for j in i .. n-1
if (a[j] > a[j+1])
swap(a[j], a[j+1])
swapped := true
return if not swapped
Example :
30 64 26 46 109 21 84 98 30 26 46 64 21 84 98 109 26 30 46 21 64 84 98 109 26 30 21 46 64 84 98 109 26 21 30 46 64 84 98 109 21 26 30 46 64 84 98 109 21 26 30 46 64 84 98 109
When no swaps that means input is sorted now.
Notes :
- O(N^2) time complexity in worst, and average cases.
- O(N) time complexity in best case if input is already sorted or nearly sorted.
- Exchanges only adjacent elements, which is really slow.
- It is stable and in-place sorting algorithm.
- Best case swaps is O(1), and worst case is O(N^2)
- Best case comparisons is O(N), and worst case is O(N^2)
Please write comments if you find anything incorrect. A gentle request to share this topic on your social media profile.
