19. Bubble Sort
Repeatedly swap adjacent items that are out of order. Each pass bubbles the largest remaining item to the end. O(n^2), mainly a teaching tool.
How it works
Walk the array comparing neighbors and swap any pair in the wrong order. After pass 1 the maximum is in the last slot; after pass k the last k slots are final. If a pass makes no swaps, the array is sorted and we stop early, which makes bubble sort O(n) on already-sorted input.
Diagram
flowchart LR
s0["5 2 9 1 6 3"]
s1["2 5 1 6 3 9"]
s2["2 1 5 3 6 9"]
s3["1 2 3 5 6 9"]
s4["1 2 3 5 6 9"]
s0 -->|"pass 1"| s1
s1 -->|"pass 2"| s2
s2 -->|"pass 3"| s3
s3 -->|"pass 4"| s4
Step-by-step trace
Input: Sort [5, 2, 9, 1, 6, 3].
| Pass | Swaps made | Array after pass | Sorted tail |
|---|---|---|---|
| start | - | [5, 2, 9, 1, 6, 3] | [] |
| 1 | 5<->2, 9<->1, 9<->6, 9<->3 | [2, 5, 1, 6, 3, 9] | [9] |
| 2 | 5<->1, 6<->3 | [2, 1, 5, 3, 6, 9] | [6, 9] |
| 3 | 2<->1, 5<->3 | [1, 2, 3, 5, 6, 9] | [5, 6, 9] |
| 4 | none (stop early) | [1, 2, 3, 5, 6, 9] | [3, 5, 6, 9] |
Result: Sorted: [1, 2, 3, 5, 6, 9].
Complexity
| Operation | Time | Space |
|---|---|---|
| Worst / average | O(n^2) | O(1) |
| Best (already sorted, early exit) | O(n) | O(1) |
| Stable? | yes | - |
Python reference implementation
def bubble_sort(a):
a = list(a)
n = len(a)
for end in range(n - 1, 0, -1):
swapped = False
for i in range(end):
if a[i] > a[i + 1]:
a[i], a[i + 1] = a[i + 1], a[i]
swapped = True
if not swapped:
break # already sorted: stop early
return a
Common mistakes and tips
- Without the
swappedflag the best case is still O(n^2). - Each pass can stop one position earlier because the tail is already final.
The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.
| Previous: Minimum Spanning Tree (Kruskal’s Algorithm) | Next: Insertion Sort |