Skip to main content
← All posts

Insertion Sort: Mechanism, Complexity Analysis & Interactive Visualizer

Md. Harun-Or-RoshidNov 5, 20268 min readArticle
Insertion Sort: Mechanism, Complexity Analysis & Interactive Visualizer
Basic Sorting · Article 4 of 62

Insertion Sort

Take each new element and slide it left over larger neighbors until it lands in the right slot — like sorting a hand of cards.

How it works

Insertion Sort grows a sorted prefix one element at a time. For each new element, it shifts larger neighbors right by one position to open a slot, then drops the element in.

  1. The first element forms a trivially-sorted prefix of length 1.
  2. Pick the next element as the key.
  3. Compare against elements in the sorted prefix from right to left, shifting any that are greater than the key.
  4. Insert the key in the resulting gap.

The shift is what makes Insertion Sort stable and adaptive: on a nearly-sorted array it runs in close to linear time because almost no shifts are needed.

Complexity

Best time
O(n)
Average time
O(n²)
Worst time
O(n²)
Extra space
O(1)
Stable
Yes
In-place
Yes
Insertion Sort is the gold standard for small arrays. Every fast hybrid sort (TimSort, IntroSort, std::sort) switches to it once the recursive subproblem drops below ~16 elements.

Interactive visualization

Pseudocode

procedure insertionSort(A):
  for i from 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

JavaScript implementation

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

Pros and cons

Pros

  • Best case O(n) on already-sorted input — adaptive.
  • Stable, in-place, online (can sort as data arrives).
  • Excellent constant factors; fastest practical sort for n < ~20.
  • Branch-friendly memory access pattern.

Cons

  • Quadratic worst case on reversed input.
  • Shift dominated — O(n²) writes, unlike Selection Sort.
  • Doesn't scale to large n.

When to use it

  • Base case in hybrid sorts (TimSort, IntroSort).
  • Almost-sorted streams where best-case linearity wins.
  • Tiny arrays in any setting.
Up next: Binary Insertion Sort — a much older idea — gap-based exchanges from Shell that beat O(n²) without recursion.
Share:
Share on X
Share on LinkedIn
Share on Facebook
Share on Reddit
Share on WhatsApp
Share on Telegram
Copy link

Related reading

Insertion Sort Sorting Algorithm & Guide | Draftsbook · Draftsbook