Lesson 03 · Data structures · 11 min
Bubble sort and selection sort
The two sorts everyone learns first, pass by pass, with the comparisons counted and a quiet lesson about stability hiding in my notes.

After this you can
- Run bubble and selection sort by hand and count their comparisons
- Know why both are O(n²), and when that's still the right choice
- Tell a stable sort from an unstable one, and why it matters for real data
This page of my notebook is all passes. Bubble sort on 3, 7, 1, 4, 5, selection sort on 8, 3, 5, 7, 1, 4, 2, then selection sort again on 48, 91, 22, 4, 48, 15, largest first. At the top are two formulas I copied down: passes = n − 1, and comparisons on a pass = n − pass. Both sorts are slow, and both are worth knowing anyway, because they make you see what a sorting algorithm actually spends its time on.
Watch them work
Start. Nothing is sorted yet.
- Pass
- 0
- Compares
- 0
- Swaps
- 0
- passes will be written here
Step through it with the arrows. The pass log at the bottom is written the way I wrote it on paper, with a bar between the part that's finished and the part that isn't.
Bubble sort
Walk along the list comparing neighbours, and swap any pair that's out of order. By the end of the first pass the biggest value has bubbled all the way to the right, into its final place. The next pass can stop one place earlier, and so on. That's where my formulas come from: with n items you need at most n − 1 passes, and pass p makes n − p comparisons.
Add those up and you get (n − 1) + (n − 2) + … + 1 = n(n − 1) / 2 comparisons. For my five numbers that's 10. For a thousand numbers it's 499,500.
There's an easy saving my page doesn't use. Look at my passes: the list is already sorted after pass 2, but I kept going for passes 3 and 4. If a whole pass makes no swaps, nothing is out of order, so you can stop. With that check my example takes 9 comparisons instead of 10, and an already-sorted list takes just one pass, n − 1 comparisons.
def bubble_sort(a): a = list(a) n = len(a) for p in range(1, n): # n - 1 passes at most swapped = False for j in range(n - p): # n - p comparisons on pass p if a[j] > a[j + 1]: a[j], a[j + 1] = a[j + 1], a[j] swapped = True if not swapped: # a pass with no swaps: done break return aprint(bubble_sort([3, 7, 1, 4, 5])) # [1, 3, 4, 5, 7]Selection sort
Selection sort is how most people sort a hand of cards. Find the smallest of what's left, put it next in line, repeat. It always makes exactly n(n − 1) / 2 comparisons, sorted input or not, because it can't know something is the smallest without checking everything else. But it makes at most n − 1 swaps, one per pass. Bubble sort can make a swap for every comparison.
def selection_sort(a): a = list(a) n = len(a) for i in range(n - 1): m = i for j in range(i + 1, n): if a[j] < a[m]: m = j a[i], a[m] = a[m], a[i] # one swap per pass return aprint(selection_sort([8, 3, 5, 7, 1, 4, 2])) # [1, 2, 3, 4, 5, 7, 8]What my page does differently
Look closely at my selection passes and they aren't textbook. After pass 1 the textbook version gives 1, 3, 5, 7, 8, 4, 2, because 1 and 8 swap places and 8 lands in the middle. My page says 1 | 8, 3, 5, 7, 4, 2. I lifted the 1 out and slid everything else along one place. I did that on every pass, on both examples.
It looks like a slip, but it changes something real. Pick Selection · my page and the 48 91 22 4 48 15 ↓ input in the player. The two 48s are tagged a and b. Sliding keeps 48a ahead of 48b, the way they started. Swapping can throw an item past its twin. A sort that keeps equal items in their original order is called stable.
def stable_selection_sort(a, key=lambda x: x): a = list(a) for i in range(len(a) - 1): m = i for j in range(i + 1, len(a)): if key(a[j]) < key(a[m]): m = j a.insert(i, a.pop(m)) # lift it out, slide the rest along return acards = [(2, "a"), (2, "b"), (1, "c")] # sort by the number onlyprint(stable_selection_sort(cards, key=lambda c: c[0]))# [(1, 'c'), (2, 'a'), (2, 'b')] a is still before b# Swapping instead of sliding gives [(1, 'c'), (2, 'b'), (2, 'a')]Stability is what lets you sort by more than one thing. Sort a list of payments by date, then stable-sort it by customer, and each customer's payments are still in date order. Python guarantees its built-in sort is stable for exactly this reason. Sliding costs more moves than swapping (up to n per pass instead of one), so you're trading writes for stability.
Why n² hurts
| n | n(n − 1) / 2 comparisons | n log₂ n, for scale |
|---|---|---|
| 10 | 45 | ≈ 33 |
| 100 | 4,950 | ≈ 664 |
| 10,000 | ≈ 50 million | ≈ 133,000 |
| 1,000,000 | ≈ 500 billion | ≈ 20 million |
Double the input and an n² sort does four times the work. At a million items that's the difference between well under a second and hours. Merge sort, quicksort and heapsort get to about n log n, and that's the best any sort that only compares items can do.
Where you'll meet these
Tiny arrays
Sorting five sensor readings on a microcontroller, or the top three scores. The setup cost of a fancy sort is bigger than the sort.
Expensive writes
When moving data costs much more than reading it (flash memory wears out with writes), selection sort's at most n − 1 swaps can be the point.
Nearly sorted data
A sorted list with one new item on the end: insertion sort fixes it in one pass. Bubble sort only does if the new item is big. A small one crawls left one place per pass, the “turtle” problem.
Multi-key sorting
Any table you sort by one column and then another relies on stability, the property my lift-and-slide version has.
Try it
01Without the early stop, how many comparisons does bubble sort make on 6 items?
Show the answerHide the answer
02Is bubble sort stable?
Show the answerHide the answer
03Run textbook selection sort (swapping) on 2a, 2b, 1. What comes out?
Show the answerHide the answer
04Bubble sort's best case is n − 1 comparisons. What's selection sort's?
Show the answerHide the answer
Further reading
- Python: Sorting Techniques ↗
Keys, stability and multi-key sorts, from the people who wrote the sort.
- VisuAlgo: sorting ↗
Bubble, selection, insertion, merge, quick and more, animated side by side.
- Sorting algorithm (Wikipedia) ↗
The big comparison table: time, memory and stability for every common sort.