Imagine bubbles rising to the top of a glass — the biggest bubbles reach the top first. Bubble sort works the same way: larger values "bubble up" to the end of the list.
Bubble sort repeatedly steps through the list, compares adjacent items, and swaps them if they're in the wrong order. Each "pass" places the next largest value in its correct position.
Algorithm:
For i from 0 to n-2: # Number of passes
For j from 0 to n-2-i: # Compare adjacent pairs
If items[j] > items[j+1]:
Swap items[j] and items[j+1]
Trace example: [64, 34, 25, 12]
Pass 1: [34, 25, 12, 64] ← 64 bubbled to end
Pass 2: [25, 12, 34, 64] ← 34 bubbled into place
Pass 3: [12, 25, 34, 64] ← Sorted!
def bubble_sort(items):
n = len(items)
for i in range(n - 1):
swapped = False
for j in range(n - 1 - i):
if items[j] > items[j + 1]:
items[j], items[j + 1] = items[j + 1], items[j]
swapped = True
if not swapped: # No swaps = already sorted!
break
return items
swapped flag lets us stop early if the list is already sorted. In the best case (already sorted), bubble sort only makes one pass — O(n).
Think about how you sort a hand of playing cards. You pick up one card at a time and insert it into the correct position among the cards you're already holding. That's insertion sort!
The algorithm builds the sorted list one element at a time. It takes each element and inserts it into its correct position in the already-sorted portion.
Algorithm:
For i from 1 to n-1:
key = items[i] # The element to insert
j = i - 1 # Start from the previous element
While j >= 0 AND items[j] > key:
items[j+1] = items[j] # Shift right
j = j - 1
items[j+1] = key # Insert key in correct position
Trace: [64, 34, 25, 12]
i=1, key=34: [34, 64, 25, 12] ← 34 inserted before 64
i=2, key=25: [25, 34, 64, 12] ← 25 inserted at start
i=3, key=12: [12, 25, 34, 64] ← 12 inserted at start
| Criteria | Bubble Sort | Insertion Sort |
|---|---|---|
| Best case | O(n) with flag | O(n) — already sorted |
| Worst case | O(n) | O(n) |
| Swaps | Many swaps | Shifts, fewer swaps |
| Stable? | Yes | Yes |
| Use case | Educational, small data | Small/partially sorted data |