Skip to main content
Beginner ~10 min read

Insertion Sort

Grow a sorted region one element at a time, like sorting cards in your hand. Excellent on small or nearly-sorted data.

Prerequisites: Arrays: Traversal, Insertion & Deletion, Big O Notation & Time Complexity

Insertion sort grows a sorted region at the front of the array. Take the first unsorted element (the key), scan backward through the sorted region, shift every larger element one slot right, and drop the key into the gap. The sorted region grows by one. It's exactly how most people sort playing cards: hold the sorted cards in your left hand, pick a new card, slide it into place.

Its superpower is adaptivity. If the array is already sorted, each key needs one comparison and zero shifts, O(n) total. Nearly-sorted data (every element within a few slots of home) costs O(n + inversions), which is nearly linear. That property, plus tiny constants and O(1) space, is why production sort libraries (Timsort in Python/Java, V8's Array.prototype.sort) switch to insertion sort for small runs, it beats fancy algorithms below ~16–32 elements.

Trace: [7, 3, 5]

  1. 1

    Key = 3 (index 1)

    7 ≥ 3 → shift 7 right → [7, 7, 5]; gap at index 0. Drop 3 → [3, 7, 5]. Sorted prefix: [3, 7].

  2. 2

    Key = 5 (index 2)

    7 ≥ 5 → shift → [3, 7, 7]; now 3 < 5 → stop. Drop 5 into the gap → [3, 5, 7].

  3. 3

    Result

    3 comparisons, 3 shifts. Note the vocabulary: insertion sort SHIFTS (single writes), bubble sort SWAPS (double writes), shifting is cheaper.

Implementation

insertion-sort.js
// Pure: returns a new sorted array. Stable.
function insertionSort(input) {
  const arr = [...input];
  for (let i = 1; i < arr.length; i++) {
    const key = arr[i];               // pick up the key
    let j = i - 1;
    while (j >= 0 && arr[j] > key) {  // scan the sorted region backward
      arr[j + 1] = arr[j];            // shift right (single write)
      j--;
    }
    arr[j + 1] = key;                 // drop the key into its gap
  }
  return arr;
}
Operation / caseCostNotes
Best case (sorted)O(n)one comparison per key, no shifts
Nearly sortedO(n + inversions)adaptive, few shifts
Average & worst (reversed)O(n²)every key shifts past everything
SpaceO(1)in-place, one held key
Stable?Yesstrict > in the shift test never jumps equal keys

Check your understanding

  1. 1.Insertion sort's best case is O(n). Which input achieves it?
  2. 2.Why do shifts cost less than bubble sort's swaps?
  3. 3.Which statement about stability is correct?

Finished reading?

Mark it complete to earn +50 XP. Progress stays in your browser.

Visualize it

Insertion Sort

Play, pause, and scrub the real algorithm step by step.

Play it

Sorting Arena

Sort the bar array yourself using swaps, then find out how your move count compares to the theoretical minimum…

Keep going