Bubble Sort
The name “bubble sort” comes from the way larger values bubble up to the top (right end) of the list with each pass. It was described formally by American mathematician Edward Friend in 1956 and popularised in CS education throughout the 1960s and 1970s. Today it is famous mainly as the algorithm every CS student learns first — not because it is fast, but because its simplicity makes it the perfect teaching example.
How it works
Walk across the array from left to right. Every time you see two neighbouring elements that are out of order (left bigger than right), swap them. After one full walk, the biggest element has bubbled all the way to the far right — its final position. Walk again, but ignore that last element. Keep going until a full pass makes zero swaps: the array is sorted.
📚 Real-world analogy: Sorting a row of books by height. You keep walking along the shelf, swapping taller books to the right whenever they are next to a shorter neighbour, until the tallest book reaches the end. Repeat with the remaining books.
The early-exit optimisation
If a complete pass makes zero swaps, every pair is already in order and the algorithm exits immediately. On an already-sorted input, this makes the best case O(n) instead of the naive O(n²). Without it, Bubble Sort would waste time on passes that accomplish nothing.
🧠 Key insight: The early-exit flag is what separates a smart Bubble Sort from a naive one. It also exposes Bubble Sort’s main weakness: the “turtle problem” — small values near the right end move leftward only one position per full pass. Cocktail Shaker Sort (below) was invented specifically to fix this.
Complexity: Best O(n) Average O(n²) Worst O(n²) Swaps O(n²) Stable ✅ Adaptive ✅