Skip to content
← Notes

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.

My handwritten notes: Bubble and selection sort, worked pass by pass

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
  1. passes will be written here
Same input, same answer; what changes is how many comparisons and moves it costs to get there.

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.

bubble sort, with the early stoppython
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.

selection sortpython
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.

stable selection sort: lift and slide, as on my pagepython
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

nn(n − 1) / 2 comparisonsn log₂ n, for scale
1045≈ 33
1004,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 answer
15: 5 + 4 + 3 + 2 + 1, or 6 × 5 / 2.

02Is bubble sort stable?

Show the answer
Yes. It only swaps neighbours that are strictly out of order, so two equal items never pass each other.

03Run textbook selection sort (swapping) on 2a, 2b, 1. What comes out?

Show the answer
1, 2b, 2a. The first pass swaps 1 with 2a, sending 2a past 2b. That's instability in three items.

04Bubble sort's best case is n − 1 comparisons. What's selection sort's?

Show the answer
Still n(n − 1) / 2. It has to check every remaining item to be sure it has the smallest, sorted or not.

Further reading

07 · Contact

Write to me.

I'm open to software engineering and data roles, and to freelance work. If you have a process that still runs on copy and paste, I'd like to hear about it.