Bubble Sort in Data Structure
Bubble Sort is one of the simplest sorting algorithms taught in data structures. It repeatedly compares adjacent elements in an array and swaps them if they are out of order, causing larger values to 'bubble up' toward the end of the array with each pass.
Dry Run Example
Sorting [5, 3, 8, 1]: Pass 1 compares (5,3)→swap, (5,8)→no swap, (8,1)→swap, giving [3, 5, 1, 8]. Pass 2 compares (3,5)→no swap, (5,1)→swap, giving [3, 1, 5, 8]. Pass 3 compares (3,1)→swap, giving the fully sorted [1, 3, 5, 8].
def bubble_sort(arr):
n = len(arr)
for i in range(n - 1):
for j in range(n - 1 - i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
Complexity
| Case | Time |
|---|---|
| Best (with early-exit flag) | O(n) |
| Average/Worst | O(n²) |
Where It Fits in DSA
- Commonly used as the first sorting algorithm taught due to its intuitive logic.
- Rarely used in production code due to poor performance on large datasets.
- Useful for teaching concepts like stability and in-place sorting.
The Early-Exit Optimization
Plain bubble sort always runs every pass even if the array is already sorted, which wastes time. A single boolean flag fixes that: if a full pass makes no swaps, the data is already in order and you can stop immediately. This is what turns the best case into O(n) for nearly-sorted input.
def bubble_sort(arr):
n = len(arr)
for i in range(n - 1):
swapped = False
for j in range(n - 1 - i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
if not swapped:
break
return arr
Notice the inner loop shrinks by i each round. After pass one the largest value is parked at the end, so there is no reason to compare it again.
Why It Is Stable and In-Place
Bubble sort swaps only when arr[j] is strictly greater than its neighbour, never when they are equal. Equal keys therefore keep their original order, which makes the sort stable — valuable when you sort records by one field after already sorting by another. It also uses no extra array, just a temporary swap, so it is in-place with O(1) extra memory. These two properties, not speed, are why it appears so often in teaching.
When a Simple Sort Still Makes Sense
- Tiny arrays where the quadratic cost is irrelevant and simple code is safer.
- Data that is already almost sorted, where the early-exit version runs close to linear time.
- Learning exercises for stability, in-place swapping and loop-invariant reasoning.
It is worth comparing bubble sort with its close cousins, since beginners often meet all three together. Selection sort also runs in O(n squared) but makes far fewer swaps, because it picks the smallest remaining value and places it once per pass. Insertion sort is usually the fastest of the three on nearly-sorted or small data and is also stable, which is why it, not bubble sort, is the one often used inside hybrid sorting algorithms for tiny sub-arrays.
For anything larger, reach for an O(n log n) algorithm. A common mistake is leaving out the early-exit flag and then claiming bubble sort "has a best case of O(n)" — it does not without that flag. Another is comparing with >= instead of >, which quietly destroys stability by swapping equal elements.
Takeaway: bubble sort trades speed for simplicity and stability. Keep the swap flag, shrink the inner loop each pass, and treat it as a teaching tool rather than a production sorter.