Data Structures · Sorting

Insertion Sort

🔢 The array a[] with the key and its gap

sorted prefixkey (lifted out)the gap (value shifted away)untouched
result

🧾 Pass-by-pass record

💬 Current step

💻 The algorithm (courseware-style C++)

Yellow = the line being executed. The recipe: lift the key → shift larger values right → drop the key into the gap.

📄 Key points

1Lift key = a[i]; index i becomes a gap
2Compare right to left: a[j] > key shifts one slot right
3a[j+1] = key lands the key; the sorted prefix grows
4Nearly sorted input is fastest: best O(n), worst O(n²)
Why “direct insertion”? Each new element is put straight into its correct place inside the already sorted prefix — no jumping, no grouping.
Complexity: comparison count depends on how reversed the data is; best case (sorted) n−1 comparisons and 0 shifts; worst and average n(n−1)/2 comparisons and shifts → time O(n²), space O(1).
Properties: it shifts only when a[j] > key, so equal values never cross → stable; and it is extremely fast on nearly sorted data, which is why quicksort and merge sort often finish small ranges with it.
Versus bubble sort: a bubble swap costs three assignments, while insertion shifts one slot and places the key once — fewer real movements.
Speed
Shortcuts: Space play/pause · ←→ step · R reset · E result