Bubble Sort
Walk the array. If two neighbours are out of order, swap them. Repeat. The biggest values bubble to the end one pass at a time — that's the whole algorithm.
Adjacent swaps until sorted
- comparisons
- 0
- result
- —
- 0
def bubble_sort(arr): - 1
n = len(arr) - 2
for i in range(n): - 3
swapped = False - 4
for j in range(0, n - i - 1): - 5
if arr[j] > arr[j + 1]: - 6
arr[j], arr[j + 1] = arr[j + 1], arr[j] - 7
swapped = True - 8
if not swapped: - 9
break
What you just watched
Each pass walks the array once, comparing every adjacent pair. A pair that's out of order gets swapped. After pass 1, the largest value is guaranteed to be at the end — it bubbled all the way up. After pass 2, the two largest are at the end. And so on. The list is sorted after at most n passes.
Bubble sort is famously slow: O(n²) in the worst and average case. For 10 elements it's fine. For 10,000 it's painful. Smarter algorithms (merge sort, quicksort) hit O(n log n) by being clever about which comparisons to skip.
Try the Worst case button — it reverses the array so every comparison fires a swap. Then try Sort after a fresh shuffle and watch the early-exit kick in if the array happens to be nearly sorted.
The point of teaching bubble sort isn't to use it — most languages ship a much better sort built in. The point is that you can read the whole algorithm in five lines of code, watch each comparison happen, and feel why n × n comparisons gets expensive fast.