Privacy note: We capture your IP address to provide customised and focused services. See our Privacy Policy.

Algorithms & Competitive Programming — Alpha School

Lesson 5: Simple Sorts — Bubble, Selection and Insertion

Sorting is the first algorithm most programmers meet, and the simple sorts are the right place to start — not because you will use them in a contest (you will use the built-in sorted() instead), but because they teach the ideas that all sorting is built from: comparing, swapping, and the invariant — the promise that stays true after each step. Each simple sort is O(n^2) in the worst case, but each one has a different character, and understanding the differences teaches you how to think about algorithms at all.

Bubble sort walks through the list again and again, swapping neighbours that are out of order, so the largest unsorted value bubbles to the end on each pass. Selection sort finds the smallest remaining value and swaps it into place, one position at a time. Insertion sort takes each new value and inserts it into the already-sorted part, shifting larger values aside — exactly how you sort a hand of cards. The code below shows insertion sort, the most useful of the three: it is fast on nearly-sorted data, it is stable, and it sorts in place.

def insertion_sort(items):
    items = list(items)
    for i in range(1, len(items)):
        key = items[i]
        j = i - 1
        while j >= 0 and items[j] > key:
            items[j + 1] = items[j]
            j -= 1
        items[j + 1] = key
    return items


print(insertion_sort([5, 2, 4, 1, 3]))  # [1, 2, 3, 4, 5]
print(insertion_sort([1, 2, 3, 5, 4]))  # nearly sorted: very few shifts

Invariants, stability, and when simple is fine

The invariant of insertion sort is that after each pass, the first i items are sorted. That single sentence is the key to proving the algorithm correct: if the first i items are sorted and you insert the next one in the right place, the first i + 1 are sorted too. Thinking in invariants is a skill that transfers to every algorithm in this course — dynamic programming and graph search both become far easier once you can state what stays true at each step.

Two more words belong in your vocabulary. A sort is stable if equal items keep their original relative order — important when you sort by one key and then another, as in sorting students by name and then by grade. Insertion sort is stable; selection sort is not. And a sort is in place if it uses only O(1) extra space. All three simple sorts are in place, but all three are O(n^2), so for large inputs you need the faster sorts of the next lesson. The simple sorts still have their place: for tiny inputs, or nearly-sorted data, insertion sort is often the fastest thing in the room.

Going further

Bubble sort has one redeeming feature: it can stop early. If a full pass makes no swaps, the list is already sorted, and the algorithm can finish immediately. That makes bubble sort O(n) on sorted input — its best case — even though its worst case stays quadratic. The early-exit flag is a small change with a real lesson in it: an algorithm that checks whether its work is done, instead of blindly repeating, is often dramatically faster on the easy inputs that appear in practice. The same idea, detecting that nothing changed, appears in graph algorithms and in iterative improvement methods.

The simple sorts also have a specialised cousin worth knowing: counting sort. If the values come from a small range — say, exam scores from 0 to 100 — you can count how many of each value there are, then write them out in order. Counting sort runs in O(n + k) time, where k is the range of values, which beats O(n log n) when the range is small. It is not a general-purpose sort, but it is a reminder that extra information about the input can break the limits that apply to general algorithms.

To make the idea of an invariant concrete, try proving bubble sort correct in one sentence: after each pass, the largest unsorted value has bubbled to its final position, so after k passes the last k values are sorted and will never move again. That sentence is the whole proof, and it also tells you an optimisation — each pass can stop one item earlier, because the tail is already sorted. Invariants are not just a theoretical device; they are a debugging tool. When a sort misbehaves, check whether the invariant holds after each pass, and the broken step will show itself.

Key Terms

Bubble sort
Repeatedly swaps neighbouring out-of-order items, bubbling the largest value to the end each pass.
Selection sort
Repeatedly finds the smallest remaining value and swaps it into its final position.
Insertion sort
Inserts each new value into its correct place among the already-sorted items, like sorting cards in hand.
Invariant
A statement that stays true after each step of an algorithm, used to reason about correctness.
Stable sort
A sort that keeps equal items in their original relative order.
In place
An algorithm that uses only O(1) extra space beyond the input.
Swap
Exchanging two values; in Python, a, b = b, a.

Discussion Questions

  1. Why is insertion sort fast on nearly-sorted data but slow on reversed data? Trace it on [1, 2, 3, 5, 4] and on [5, 4, 3, 2, 1].
  2. Why does stability matter? Give an example where an unstable sort would give a wrong-looking result.
  3. If Python's built-in sorted() exists, why learn bubble, selection and insertion sort at all?

Practice Questions

  1. What is the invariant of insertion sort?
  2. Trace insertion sort on [3, 1, 2]. What is the list after the first pass (i = 1)?
  3. Which of the three simple sorts is stable, and why does it matter?
  4. All three simple sorts are O(n²) worst-case. When is insertion sort still a good choice?
  5. What is the worst-case complexity of bubble sort, and why?
Show answers
  1. After each pass, the first i items are sorted. Inserting the next item in its correct place extends the sorted part by one.
  2. [1, 3, 2]. The key 1 is inserted before 3; the 2 has not been processed yet.
  3. Insertion sort (and bubble sort); selection sort is not. Stability keeps equal items in their original order, which matters when sorting by multiple keys.
  4. For small inputs or nearly-sorted data. On nearly-sorted data it does very few shifts — close to O(n).
  5. O(n²). Each of the n passes scans up to n neighbours, comparing and possibly swapping.
Keep reading to complete this lesson