Log inStart free
LESSON 3.08 · 6 STAGES · 2 CONTROLS · 3 CHECKSPRO · PREVIEW

Sorting and divide-and-conquer

Watch three sorts order the same 8 numbers, and count every comparison.


Pro lesson. Stage 1 is free to watch. Pro opens all 6 stages, 2 controls and 3 checks, in this lesson and every other.

Go Pro · $8.25/mo
EXPLAINER · 3.08 · SORT BAYINSERTION SORT · 20 COMPARISONS · WORST 28
01
Stage 1 of 6 · Insertion sort
Insertion sort moves each next item up past the larger items. This costs 20 comparisons.
Explain it simply

Think of sorting cards in your hand. Each column shows the list after one more item finds its place in the sorted part at the top. The number under a column counts its comparisons. Item 2 can pass at most 1 item, item 3 at most 2, and so on. So the worst case adds up fast.

Eight columns show insertion sort on 66, 16, 89, 74, 36, 96, 21, 45. The steps cost 1, 1, 2, 4, 1, 6 and 5 comparisons, 20 in all.

item (bar = value)pivotfinal place, comparisonsgroup, n log₂ nworst case n(n−1)/2
insertion sortcomparisonsinput6616897436962145insert 1616668974369621451insert 8916668974369621451insert 7416667489369621452insert 3616366674899621454insert 9616366674899621451insert 2116213666748996456insert 4516213645667489965comparisons · 8 itemsinsertion sort20merge sort–quicksort–worst n(n−1)/2 = 28n log₂ n = 24insertion sortcomparisonsinput6616897436962145insert 1616668974369621451insert 8916668974369621451insert 7416667489369621452insert 3616366674899621454insert 9616366674899621451insert 2116213666748996456insert 4516213645667489965comparisons · 8 itemsinsertion sort20merge sort–quicksort–worst n(n−1)/2 = 28n log₂ n = 24
Toy: 8 numbers · 3 sorts · each column is the list after one step · the chart runs 8 to 64 items
STAGE 1 / 6
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
C≤1+2+⋯+(n−1)=n(n−1)2\sy{C}{out}{C} \le 1 + 2 + \dots + (\sy{n}{data}{n} - 1) = \frac{n(n-1)}{2}
C=1+1+2+4+1+6+5=20≤28C = 1 + 1 + 2 + 4 + 1 + 6 + 5 = 20 \le 28

Item i compares with at most i items above it.

Common mix-ups

MYTHQuicksort is always the fastest of the three.

The fix, and 1 more mix-up with the diagram to show them, come with Pro.

Predict, then reveal
3 CHECKS · PRO
Q01With nearly sorted input, which sort needs the fewest comparisons?

Make your guess, then test it in the diagram. All 3 checks come with Pro.

PRO LESSON · YOU WATCHED STAGE 1 OF 6
Unlock the full explainer
  • 5 more stages and 2 live controls
  • 2 mix-up cards and 3 predict-then-reveal checks
  • Watch it as a narrated video, in three voices
  • Every Pro lesson and capstone · 656 in total

$99 a year, or $15 a month. Cancel any time.