Three ways to grow a sorted region
All three algorithms keep a sorted region and grow it by one element per pass. They differ in where the region lives and how the next element joins it.
| Algorithm | Sorted region | One pass |
|---|---|---|
| Bubble sort | the end of the array, final values | walk left to right, swapping neighbours that are out of order; the largest remaining value "bubbles" to the end |
| Selection sort | the front, final values | scan the unsorted part for its minimum and swap it to the front of that part |
| Insertion sort | the front, sorted among themselves but not final | take the next element and shift larger ones right until its place opens |
The lab above runs selection sort. Bubble sort and insertion sort have their own visualizers with the same controls and the same 3D array: bubble sort visualizer and insertion sort visualizer. Try the same input in all three.
Selection sort
For each position i from 0 to n − 2:
- Assume the minimum of
items[i..]is ati(minIndex = i). - Compare every later element with the current minimum; a strictly smaller one becomes the new minimum.
- Swap
items[i]withitems[minIndex](skip it if they are the same slot).
Invariant: before pass i, slots 0..i−1 hold the i smallest values in sorted order, and
they never move again. In the lab, final slots turn green from the left.
Selection sort does the same comparisons whatever the input: n − 1 in the first pass, n − 2 in the next, so always n(n − 1)/2. Even a sorted array costs 28 comparisons for eight elements (the Already sorted preset). In exchange it makes at most n − 1 swaps, fewer than either of the others in the worst case. That is its one real strength: when writing an element is far more expensive than comparing two, selection sort minimises writes.
Why selection sort is not stable
Run the Not stable preset: 5a 5b 1. The minimum, 1, is at index 2, so the first pass swaps it
with index 0. That long-distance swap throws 5a past 5b:
5a 5b 1 → 1 5b 5a
Nothing later puts them back, because 5b is not strictly smaller than 5a. The swap is the
problem, not the comparison: replacing it with "remove the minimum and shift everything between
right by one" makes selection sort stable, at the price of O(n²) writes.
Bubble sort
Each pass compares neighbours items[i] and items[i + 1] from left to right and swaps them when
the right one is strictly smaller. After pass k the k largest values are final at the end. The
early exit is what makes bubble sort worth discussing: if a whole pass makes no swap, every
neighbouring pair is in order, so the array is sorted and the algorithm stops. On sorted input that
is one pass and n − 1 comparisons.
Bubble sort is stable because it only ever swaps neighbours, and only when they are strictly out of order: two equal values are never swapped, so they cannot pass each other.
Insertion sort
For each i from 1 to n − 1: lift key = items[i] out, then walk left from i − 1, shifting every
element strictly greater than key one slot right. Drop key into the gap.
Invariant: before step i, slots 0..i−1 are sorted among themselves (they are the first i
input values, rearranged). Unlike selection sort, they are not final: a later small key can still
push them right.
Insertion sort is stable (equal elements stop the shifting, so the key lands after them), works in place, and is online: it can sort elements as they arrive, because each step only needs the elements seen so far.
Inversions: why nearly sorted input is cheap
An inversion is a pair of positions i < j with items[i] > items[j]. A sorted array has 0, a
reversed one has n(n − 1)/2, and a random permutation has n(n − 1)/4 on average.
Swapping two neighbours that are out of order removes exactly one inversion. So:
- bubble sort makes exactly one swap per inversion, and
- insertion sort makes exactly one shift per inversion, with at most n − 1 extra comparisons.
If every element is at most k places from its final position, there are at most about n·k inversions, and insertion sort runs in O(n·k). This is why insertion sort is the algorithm of choice for "almost sorted" data and for small ranges.
Side by side
| Bubble (early exit) | Selection | Insertion | |
|---|---|---|---|
| Comparisons, best | n − 1 (sorted) | n(n − 1)/2 | n − 1 (sorted) |
| Comparisons, worst | n(n − 1)/2 | n(n − 1)/2 | n(n − 1)/2 |
| Element moves | 1 swap per inversion | ≤ n − 1 swaps | 1 shift per inversion + n − 1 placements |
| Stable | yes | no (swap version) | yes |
| Adaptive (faster on nearly sorted) | yes | no | yes |
| Extra space | O(1) | O(1) | O(1) |
All three are Θ(n²) in the worst case and on average. Insertion sort usually beats bubble sort in practice: a shift is one write where a swap is two (or three with a temporary), and insertion sort stops scanning as soon as the key's place is found.
Where these still run
You will rarely call a quadratic sort yourself, but the built-in sorts call insertion sort for you:
- Python (
list.sort,sorted): Timsort extends short natural runs to a minimum length (between 32 and 64) with binary insertion sort, then merges runs. - C# (
Array.Sort,List<T>.Sort): an introspective sort that switches to insertion sort for small partitions. - C++ (
std::sortin libstdc++ and libc++): introsort that finishes small ranges with insertion sort. - Java (
Arrays.sortfor primitives): a dual-pivot quicksort that uses insertion sort for very small ranges; the object sort (TimSort) uses binary insertion sort for short runs, like Python.
The exact thresholds are implementation details that change between versions. The pattern does not: divide-and-conquer sorts have a high constant per call, and below a few dozen elements insertion sort's tight loop over contiguous memory wins.
The teaching implementation
SelectionSort.Sort / selection_sort takes a comparison (or a key in Python). Because selection
sort is unstable, its shared fixture records the exact order this implementation leaves equal
keys in, for example 3a 1 3b 2 3c → 1 2 3b 3a 3c, and all four languages must reproduce it.
Each is also compared with its built-in sort on 500 random inputs (keys only, since the order of
equal keys may legitimately differ). Bubble sort and insertion sort are tested against the stable
merge sort fixture; their listings are on their visualizer pages.
Common mistakes
- Swapping on
<=in bubble sort or shifting on>=in insertion sort: still sorted, no longer stable. - Forgetting the early exit in bubble sort, which turns its best case into n(n − 1)/2.
- Updating
minIndexwith<=in selection sort: picks the last of equal minimums. Both versions are unstable, but they give different orders, so tests that pin down the exact output must agree on one. - Insertion sort writing the key on every shift instead of once at the end: correct, but twice the writes.
Worked practice
1. How many inversions does 3 1 2 have, and how many swaps will bubble sort make?
Answer
Two inversions: (3, 1) and (3, 2). Bubble sort makes exactly two swaps: 3 passes 1, then 3 passes 2.
2. You sort 1,000 records that were sorted yesterday and then had 5 records changed. Which elementary sort do you pick?
Answer
Insertion sort. Each changed record creates at most n inversions, so there are at most about 5,000, and insertion sort does roughly that many shifts plus n comparisons, far below the roughly 500,000 comparisons selection sort always makes.
3. Selection sort on 2a 2b 2c 1. What is the result?
Answer
1 2b 2c 2a. The first pass swaps 1 with 2a (index 0 ↔ 3). The remaining passes find 2b
and then 2c already in place (only strictly smaller values replace the minimum), so no more swaps.
Summary
- All three grow a sorted region one element per pass and cost Θ(n²) comparisons in the worst case.
- Selection sort: always n(n − 1)/2 comparisons, at most n − 1 swaps, not stable.
- Bubble and insertion sort: one swap or shift per inversion, stable, linear on sorted input.
- Insertion sort is the small-range workhorse inside Python's, C#'s, Java's and C++'s library sorts.