Skip to main content

Insertion Sort

Pick each key, shift larger values right, drop it into the gap, sorted region grows from the left.

time O(n²) worst, O(n) on sorted inputspace O(1)Read the lesson
BeginnerO(n²) worst, O(n) on sorted input

Pick each key, shift larger values right, drop it into the gap, sorted region grows from the left.

step 1 / 21

What's happening

Insertion sort grows a sorted region at the front, inserting each new element where it belongs, like sorting playing cards in your hand.

comparisons: 0swaps: 0writes: 0
comparingswappingkey heldwritingpivotfinal position

K marks the held key; shifts (single writes) slide larger values right. Try sorted input “1, 2, 3, 4, 5, 6”, O(n) with zero shifts.

Understand the algorithm

time O(n²) worst, O(n) on sorted inputspace O(1)

What it is

Insertion sort takes each element as a 'key' and slides it left through the already-sorted prefix until it drops into the right gap, exactly how people sort playing cards.

Why it matters

It is the fastest simple sort on small or nearly-sorted data, which is why production sorts (Timsort, introsort) hand small runs to insertion sort internally. Watching it teaches incremental maintenance of a sorted region.

How it works

  1. 1The prefix arr[0..i-1] is always sorted.
  2. 2Pick arr[i] as the key; hold it in a variable.
  3. 3Shift every prefix element larger than the key one slot right.
  4. 4Drop the key into the gap; the sorted prefix has grown by one.

Real-world uses

  • Small arrays and the small-run fallback inside Timsort/introsort
  • Online sorting, keeping a list sorted as items arrive one by one
  • Nearly-sorted data, where it approaches O(n)

Strengths

  • O(n) on sorted or nearly-sorted input, adaptive
  • Stable and in place
  • Excellent constant factors at small n

Limitations

  • O(n²) worst case on reversed input
  • Shifting many elements per insertion on random data
  • Not competitive at large n

Run it on nearly-sorted data to see why libraries use it for small runs.