Bubble Sort
Bubble sort is the simplest sorting algorithm to understand. It walks through the array comparing each pair of neighbours, and swaps them when they are in the wrong order. After the first pass the largest value has "bubbled up" to the end; after the second pass the second largest is in place, and so on.
How it works
- Compare
a[0]anda[1]; ifa[0] > a[1], swap them. - Move one step right and compare
a[1]anda[2], and so on to the end of the unsorted part. - After the pass, the last unsorted position holds its final value, so the next pass can stop one step earlier.
- Repeat. If a whole pass makes no swaps, the array is already sorted and we can stop.
Step through it below. Yellow bars are being compared, red bars were just swapped and green bars are final.
Implementation
The Python version below sorts the same array and prints every swap and the array after each pass, so you can compare it with the animation frame by frame.
def bubble_sort(arr):
n = len(arr)
for p in range(n - 1):
swapped = False
for j in range(n - 1 - p): # the last p values are already final
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
print(f" {arr[j + 1]} > {arr[j]}, so swap them")
print(f"Pass {p + 1} done: {arr}")
if not swapped:
print("No swaps in this pass, so the array is sorted.")
break
return arr
bubble_sort([6, 2, 9, 4, 1]) 6 > 2, so swap them
9 > 4, so swap them
9 > 1, so swap them
Pass 1 done: [2, 6, 4, 1, 9]
6 > 4, so swap them
6 > 1, so swap them
Pass 2 done: [2, 4, 1, 6, 9]
4 > 1, so swap them
Pass 3 done: [2, 1, 4, 6, 9]
2 > 1, so swap them
Pass 4 done: [1, 2, 4, 6, 9]
Notice that the inner loop gets shorter on every pass (n - 1 - p), because the end of the array is already sorted. Pass 4 still runs here, because pass 3 made swaps.
The early exit
The swapped flag makes bubble sort fast on data that is already sorted, or nearly so. On [1, 3, 2, 4, 5] only one swap is needed, and the second pass confirms the order:
def bubble_sort_count(arr):
n = len(arr)
comparisons = swaps = passes = 0
for p in range(n - 1):
passes += 1
swapped = False
for j in range(n - 1 - p):
comparisons += 1
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swaps += 1
swapped = True
if not swapped:
break
return arr, passes, comparisons, swaps
for data in ([1, 3, 2, 4, 5], [6, 2, 9, 4, 1], [5, 4, 3, 2, 1]):
result, passes, comps, swaps = bubble_sort_count(list(data))
print(f"{data} -> {result}: {passes} passes, {comps} comparisons, {swaps} swaps")[1, 3, 2, 4, 5] -> [1, 2, 3, 4, 5]: 2 passes, 7 comparisons, 1 swaps
[6, 2, 9, 4, 1] -> [1, 2, 4, 6, 9]: 4 passes, 10 comparisons, 7 swaps
[5, 4, 3, 2, 1] -> [1, 2, 3, 4, 5]: 4 passes, 10 comparisons, 10 swaps
A reversed array is the worst case: every comparison leads to a swap, n(n-1)/2 of each (10 for n = 5).
Properties
| Property | Bubble sort |
|---|---|
| Time, worst and average | O(n²) |
| Time, best (already sorted, with early exit) | O(n) |
| Extra memory | O(1): sorts in place |
| Stable? | Yes: equal values are never swapped (we use >, not >=) |
Stable means equal values keep their original order. That matters when sorting records by one field, for example sorting students by grade while keeping them alphabetical within each grade:
def bubble_sort_by(records, key):
n = len(records)
for p in range(n - 1):
for j in range(n - 1 - p):
if key(records[j]) > key(records[j + 1]):
records[j], records[j + 1] = records[j + 1], records[j]
return records
students = [("Ana", "B"), ("Ben", "A"), ("Cleo", "B"), ("Dev", "A")]
for name, grade in bubble_sort_by(students, key=lambda s: s[1]):
print(grade, name)A Ben
A Dev
B Ana
B Cleo
Ben stays before Dev and Ana before Cleo, exactly as in the input.
Note: Bubble sort is mostly a teaching tool. For real code use Python's
sorted()/list.sort()(Timsort,O(n log n)). Bubble sort's value is that it is easy to reason about and introduces passes, swaps, invariants and early exits.
Common mistakes
- Running the inner loop to
n - 1on every pass: still correct, but it wastes comparisons on the sorted tail. - Using
>=instead of>: still sorts, but swaps equal values and loses stability. - Off-by-one:
range(n - p)makesarr[j + 1]go out of range on the first pass.
Test yourself
After the first pass of bubble sort on [6, 2, 9, 4, 1], which value is guaranteed to be in its final place?
- 1 at the front
- 9 at the end
- 6 at the end
- Nothing yet
What does the swapped flag let bubble sort do?
- Sort in descending order
- Stop early when a pass makes no swaps
- Use less memory
- Become stable
How many swaps does bubble sort make on the reversed array [5, 4, 3, 2, 1]?
- 4
- 5
- 10
- 25