AlgoViz

Insertion sort

easy 14 min

Insertion sort builds a sorted prefix one value at a time: it takes the next value, shifts every bigger value in the prefix one slot right, and drops the value into the gap.

See it run

Grow a sorted prefix one value at a time: take the next key, shift bigger values right, and drop the key into the gap.

Operations

Sort 7 values

Sort [64, 34, 25, 12, 22, 11, 90] pass by pass. [i] marks the key being inserted, [j] walks left through the sorted prefix.

Step 1 of 15

Seven values, one already sorted

  1. 640
  2. 341
  3. 252
  4. 123
  5. 224
  6. 115
  7. 906
n = 7sorted = 1

A single value is a sorted list on its own, so the sorted prefix starts as just 64. Every pass takes the first unsorted value, the key, and inserts it into the prefix.

Step 1: Seven values, one already sorted

def insertion_sort(arr):    for i in range(1, len(arr)):          # arr[0..i-1] is already sorted        key = arr[i]                      # the value to insert        j = i - 1                         # start at the end of the sorted part        while j >= 0 and arr[j] > key:    # bigger value in the way?            arr[j + 1] = arr[j]           # shift it one slot right            j -= 1        arr[j + 1] = key                  # drop key into the gap    return arrprint(insertion_sort([64, 34, 25, 12, 22, 11, 90]))# [11, 12, 22, 25, 34, 64, 90]
Time
O(n²) worst and average
Space
O(1)
this run
16 comparisons, 14 shifts
inversions
14 = shifts

Shift, do not swap. Holding the key aside and sliding bigger values right costs one write per step instead of three.

In the real world

The same insertion sort doing real jobs. Pick one and step through it.

You hold 2, 5 and 9 in order and pick up a 7. You slide it in from the right, exactly as insertion sort does.

Step 1 of 4

Sorted hand, new card

  1. 20
  2. 51
  3. 92j
  4. 73i
key = 7

Your left hand holds 2, 5, 9, already sorted. Your right hand picks up a 7: that is the key.

Step 1: Sorted hand, new card

hand = [2, 5, 9]card = 7j = len(hand) - 1hand.append(card)while j >= 0 and hand[j] > card:    hand[j + 1] = hand[j]    j -= 1hand[j + 1] = cardprint(hand)   # [2, 5, 7, 9]

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Testing arr[j] before j >= 0

    critical

    When j reaches -1, Python does not crash: arr[-1] quietly reads the last element. The loop compares against the wrong value and can shift garbage. Put the bounds check first so short-circuiting protects the index.

    Wrong
    while arr[j] > key and j >= 0:    arr[j + 1] = arr[j]    j -= 1
    Right
    while j >= 0 and arr[j] > key:    arr[j + 1] = arr[j]    j -= 1
  • Not saving the key first

    critical

    The first shift writes over arri. If the loop keeps reading arri as the key, it compares against a value that has already been overwritten.

    Wrong
    j = i - 1while j >= 0 and arr[j] > arr[i]:   # arr[i] changes after one shift    arr[j + 1] = arr[j]    j -= 1
    Right
    key = arr[i]j = i - 1while j >= 0 and arr[j] > key:    arr[j + 1] = arr[j]    j -= 1arr[j + 1] = key
  • Writing the key at arr[j]

    critical

    When the loop stops, arrj is the first value that is not bigger than the key and must stay. The gap is one slot to its right.

    Wrong
    arr[j] = key        # overwrites a value that belongs there
    Right
    arr[j + 1] = key    # the gap is just right of j
  • Using >= in the comparison

    major

    With >= the key also jumps past values equal to it, so equal items swap their original order. The output is still sorted, but the sort is no longer stable, which breaks multi-key sorts.

    Wrong
    while j >= 0 and arr[j] >= key:   # equal values move: unstable
    Right
    while j >= 0 and arr[j] > key:    # stop at equal values: stable
  • Swapping instead of shifting

    minor

    Swapping the key leftward one neighbour at a time works, but each swap is three writes. Holding the key aside and shifting is one write per step plus one final write.

    Wrong
    j = iwhile j > 0 and arr[j - 1] > arr[j]:    arr[j - 1], arr[j] = arr[j], arr[j - 1]    j -= 1
    Right
    key, j = arr[i], i - 1while j >= 0 and arr[j] > key:    arr[j + 1] = arr[j]    j -= 1arr[j + 1] = key
  • Using it on large random data

    major

    On random input the average cost is about n²/4 shifts: 250 billion for a million values. Use the built-in O(n log n) sort; it already uses insertion sort internally for small runs.

    Wrong
    insertion_sort(million_random_values)
    Right
    million_random_values.sort()   # Timsort: O(n log n)

Interview tips

  • How to explain it

    • Like sorting cards in your hand: pick the next card and slide it into place among the cards already sorted.
    • Invariant: before pass i, arr[0..i-1] holds the original first i values in sorted order.
    • Best O(n) on sorted input, worst n(n-1)/2 shifts on reversed input, O(1) extra space.
    • Stable, in place, adaptive and online.
  • Spot it in the wild

    • Data that is nearly sorted, or has only a few values out of place.
    • Tiny arrays: hybrid sorts like Timsort and introsort switch to it below a small cutoff.
    • Values arriving one at a time into a list that must stay sorted.
  • Memory tricks

    • SCIP: Scan the next value, Compare with the sorted part, Insert it, Progress to the next.
    • Shifts = inversions. Count the out-of-order pairs and you know the cost.
    • Sorted in, n out. Reversed in, n² out.
  • Watch out

    • Bounds check first: j >= 0 before arr[j], or arr[-1] sneaks in.
    • Use > not >= to stay stable.
    • The key goes at j + 1, not j.