3.6.1 · D3Sorting & Searching

Worked examples — Bubble sort, selection sort, insertion sort — O(n²), when insertion sort wins

2,233 words10 min readBack to topic

Two words we count throughout, defined in plain terms so no symbol is unearned:

We also reuse the parent's key idea:


The scenario matrix

Every sorting input falls into one of these case classes. Each row is a distinct shape of data that makes the three sorts behave differently.

# Case class What the input looks like Which sort this stresses
A Already sorted (best case) [1,2,3,4,5] separates adaptive (insertion/bubble) from blind (selection)
B Reverse sorted (worst case) [5,4,3,2,1] maximum inversions — worst for all three
C All elements equal (degenerate) [7,7,7,7] tests early-stop and stability
D One element out of place (nearly sorted) [1,2,3,4,0] the real-world "why insertion wins" case
E Random / general mix [4,2,5,1,3] the average case
F Single element / empty (limiting) [9], [] boundary: what does give?
G Stability twist (equal keys with tags) [(2,a),(1,b),(2,c)] shows selection breaking, insertion keeping order
H Word problem (real data) daily temperatures, one late reading picks the right sort for the job

The 8 examples below hit every cell A–H.


Example A — Already sorted (best case)


Example B — Reverse sorted (worst case)


Example C — All elements equal (degenerate)


Example D — One element out of place (the "insertion wins" case)


Example E — Random mix (average case), with a figure


Example F — Single element and empty array (limiting inputs)


Example G — Stability twist (equal keys with tags)


Example H — Word problem (real data, pick the sort)


Recall Quick self-test across all cells

Best case for insertion, and its cost ::: already sorted (Cell A/D) → comparisons, . Worst case, and its move count ::: reverse sorted (Cell B) → moves = all inversions. What does every sort do on an all-equal array ::: insertion/bubble stop early → comparisons, 0 moves; selection still . Comparisons on [] or [9] ::: — the loop bound runs nothing. Why selection can break stability ::: a long-distance swap can fling an element past an equal key it never compared. The real-world case where insertion clearly wins ::: nearly-sorted data (Cell H) → cost .


See also: Big-O Notation · Inversions and Counting · Stability in Sorting · Merge Sort · Quicksort · Introsort · Lower Bound for Comparison Sorts.

#flashcards/coding

Insertion sort comparisons on [1,2,3,4,5]
(best case, ).
Insertion sort comparisons and moves on [4,3,2,1]
comparisons, moves (worst case, ).
Moves made by insertion sort on an all-equal array
— the strict-less test triggers an immediate stop.
Comparisons of selection sort on any 5-element array
always , independent of order.
Why insertion sort wins on [1,2,3,4,0]
only 4 inversions → 4 moves, , versus selection's fixed 10 comparisons.