Bubble sort repeatedly walks through the array, compares adjacent pairs and swaps them when they are out of order. After each pass the largest remaining value has "bubbled" to the end, so the sorted region grows from the right. It is rarely used in production, but it is the clearest possible introduction to comparison sorting, loop invariants and best/worst-case analysis.
Think of it like
Bubbles rising in a glass
Picture a column of bubbles of different sizes. Big bubbles rise faster and push past smaller ones until they reach the top. In bubble sort, each pass lets the biggest remaining value push past its neighbors until it reaches its final place at the end.
How it works
The algorithm makes up to n - 1 passes. In pass i, it compares a[j] with a[j+1] for every j in the unsorted part and swaps them when a[j] > a[j+1]. Because the largest value in the unsorted part is carried all the way to the right, the last i elements are always in their final positions.
- 1
Compare neighbors
Start at index 0 and look at the pair
(a[0], a[1]). - 2
Swap if out of order
If the left value is larger, swap them so the larger one moves right.
- 3
Slide the window
Move one position right and repeat until you reach the end of the unsorted part.
- 4
Shrink the range
The last element is now final. Repeat the pass on the remaining unsorted prefix.
- 5
Stop early
If a full pass makes no swaps, the array is sorted. Stop immediately.
Worked example
Sorting [5, 1, 4, 2, 8]: the first pass performs 4 comparisons and 3 swaps, moving 8 to the end. The array becomes [1, 4, 2, 5, 8].
| Pass | Array after pass | Swaps | Final positions |
|---|---|---|---|
| 1 | [1, 4, 2, 5, 8] | 3 | 8 |
| 2 | [1, 2, 4, 5, 8] | 1 | 5, 8 |
| 3 | [1, 2, 4, 5, 8] | 0 | Early exit: no swaps |
swapped flag lets the algorithm stop after pass 3 instead of running all 4 passes.Complexity analysis
In the worst case (a reversed array) every comparison causes a swap. Pass i performs n - 1 - i comparisons, so the total is the arithmetic series below.
Best case: O(n)
- Input already sorted
- One pass with n-1 comparisons, zero swaps
- Requires the early-exit
swappedflag
Worst case: O(n²)
- Input sorted in reverse
- n(n-1)/2 comparisons and as many swaps
- Every element travels the maximum distance
- Stable
- Equal elements keep their relative order, because we only swap when
a[j] > a[j+1](strictly greater). - In-place
- Uses O(1) extra memory: just a temporary variable for swapping.
- Adaptive
- With the early-exit flag, it runs faster on input that is already nearly sorted.
Turtles and rabbits
Large values near the start ("rabbits") move to the end quickly, up to one full pass at a time. Small values near the end ("turtles") move left by only one position per pass. A single small element at the end of an otherwise sorted array forces n - 1 passes. Cocktail shaker sort fixes this by alternating left-to-right and right-to-left passes.
Complexity
| Case | Time | Space | Notes |
|---|---|---|---|
| Best | O(n) | O(1) | Already sorted, with early exit |
| Average | O(n²) | O(1) | About n²/4 swaps |
| Worst | O(n²) | O(1) | Reverse-sorted input |
Stable, in-place and adaptive (with the swapped flag).
Implementation
Shrinks the inner loop each pass and exits early when no swaps occur.
def bubble_sort(a: list[int]) -> list[int]:
n = len(a)
for i in range(n - 1):
swapped = False
# The last i elements are already in place
for j in range(n - 1 - i):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
swapped = True
if not swapped: # no swaps => already sorted
break
return aKey takeaways
- Bubble sort swaps adjacent out-of-order pairs; each pass fixes the largest remaining element at the end.
- Worst and average case are Θ(n²); the best case is O(n) only with the early-exit flag.
- It is stable and in-place, which makes it a clean model for proving correctness with loop invariants.
- Small values at the end ("turtles") are what make it slow; cocktail shaker sort mitigates them.
Common pitfalls
- Forgetting to shrink the inner loop (
n - 1 - i), which wastes comparisons on the already-sorted suffix. - Using
>=instead of>in the comparison, which swaps equal elements and breaks stability. - Claiming O(n) best case without implementing the
swappedearly exit.
Interview tips
- If asked to "implement any sort", mention bubble sort's O(n²) cost and offer merge sort or quick sort instead.
- Be ready to state the loop invariant and explain why the algorithm is stable.
- Know that the number of swaps equals the number of inversions in the array, a frequent follow-up question.
Real-world applications
- Teaching comparison sorting, invariants and complexity analysis.
- Detecting whether a list is already sorted in one O(n) pass.
- Tiny embedded systems where code size matters more than speed.
Practice problems
Test yourself
What is the best-case time complexity of bubble sort with the early-exit optimization?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.