Bubble Sort Explained
Bubble Sort is the first sorting algorithm almost everyone learns. It repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order — letting larger values 'bubble' to the top. It is rarely used in production, but it is unbeatable as a teaching tool.
How Bubble Sort works
On each pass, Bubble Sort walks from the start of the array to the end, comparing each pair of neighbours. If the left element is bigger than the right, they swap. After the first pass the largest element is guaranteed to be at the end. After the second pass the two largest are in place, and so on, until the whole array is sorted.
Pseudocode
for i from 0 to n-1:
swapped = false
for j from 0 to n-2-i:
if a[j] > a[j+1]:
swap(a[j], a[j+1])
swapped = true
if not swapped:
break // already sortedThe swapped flag is the key optimization: if a full pass makes no swaps, the array is sorted and we stop early.
Complexity and the swapped-flag trick
Bubble Sort is O(n²) on average and worst case because of its nested loops. But with the early-exit flag it reaches O(n) on already-sorted data, making it adaptive. Space is O(1) and it is stable. Watch it run in the visualizer to see the largest values rise to the end pass by pass.
Should you ever use it?
In production, almost never — Insertion Sort beats it for small arrays and built-in sorts beat both. But Bubble Sort's value is pedagogical: it makes comparison and swapping crystal clear, which is why it remains the 'Hello World' of sorting. See how it compares in our Bubble vs Insertion Sort guide.
Frequently asked questions
What is the time complexity of Bubble Sort? +
Why is Bubble Sort still taught? +
Is Bubble Sort ever used in real life? +
See it in motion
Watch this algorithm and 9 others run step by step in our free interactive visualizer.
▶ Launch Visualiser