AlgoFrames

Insertion sort

Insertion sort lifts each element out and slides it left into the sorted prefix. It is fast on nearly sorted data.

Before you start: Selection sort.

The idea

You pick up a 6 while holding 2 5 7 9. You slide it in between 5 and 7 without re-sorting the hand.

The cards in your hand are already in order. Only the new card needs a place. Insertion sort repeats this for every value.

Intuition

The left part 1 4 7 is sorted. Lift the next value, 3, out of the line.

7 and 4 are bigger than 3, so each slides one cell right. The hole moves left.

3 drops into the hole. The sorted part grew by one value.

Every pass keeps the prefix sorted and adds one value to it. After n - 1 passes the prefix is the whole array.

Complexity

Sorted input needs one comparison per pass, so n - 1 in total. Reversed input shifts every value all the way left, about n²/2 moves.

The inner loop runs once per value bigger than the key. On random input that is about half the prefix, so the average is also O(n²).

It sorts inside the array and keeps only key, i and j. Extra space is O(1).

Pitfalls

With while j > 0 the loop never compares index 0. Sorting 2 5 8 1 then ends as 2 1 5 8.

Shift only while a[j] > key. With ≥ equal values jump past each other and the sort is no longer stable.

A stable sort keeps equal values in their input order. That matters when you sort records by one field after sorting by another.

Variations

Binary insertion sort finds the spot with binary search. Comparisons drop to O(log n) per value, but shifts stay O(n).

Shell sort runs insertion sort on values far apart first, such as 4 cells apart. Long moves happen early and cheaply.

Code

Pseudocode

for i ← 1 to n - 1
  key ← a[i], j ← i - 1
  while j ≥ 0 and a[j] > key
    a[j + 1] ← a[j]
    j ← j - 1
  a[j + 1] ← key
return a

Python

def insertion_sort(a):
    for i in range(1, len(a)):
        key = a[i]
        j = i - 1
        while j >= 0 and a[j] > key:
            a[j + 1] = a[j]
            j -= 1
        a[j + 1] = key
    return a

JavaScript

function insertionSort(a) {
  for (let i = 1; i < a.length; i++) {
    const key = a[i];
    let j = i - 1;
    while (j >= 0 && a[j] > key) {
      a[j + 1] = a[j];
      j--;
    }
    a[j + 1] = key;
  }
  return a;
}

Java

static int[] insertionSort(int[] a) {
    for (int i = 1; i < a.length; i++) {
        int key = a[i];
        int j = i - 1;
        while (j >= 0 && a[j] > key) {
            a[j + 1] = a[j];
            j--;
        }
        a[j + 1] = key;
    }
    return a;
}

Cost at a glance

BestO(n)
AverageO(n²)
WorstO(n²)
SpaceO(1)
Stableyes
In-placeyes
Adaptiveyes

Practice problems (6)

State after inserting the 4th element Warm-up

Insertion sort runs on [6, 3, 8, 2, 7, 1]. Show the array right after the 4th element, 2, has been inserted into the sorted prefix. Then answer two questions about how 2 gets there.

Best-case input Warm-up

All three arrays hold the same five values. On which one does insertion sort do the least work?

Implement insertion sort Standard

Sort nums in ascending order with insertion sort and return it. Sort in place: shift bigger values right instead of building a new array.

Count the shifts Standard

Return how many times insertion sort shifts a value one cell to the right while it sorts nums ascending. A key that stays where it is costs no shift.

Spot the bug: the first cell Standard

This insertion sort returns a wrong order for some inputs. Click the line with the bug, then fix it.

Insertion sort on a linked list Challenge

Sort a singly linked list ascending with insertion sort and return the new head. Reuse the existing nodes: relink them instead of creating new ones.

A list has no index, so you cannot shift values left. Walk from the front of the sorted part to find each node's place instead.

Next on the path: Merge sort