Insertion Sort: Mechanism, Complexity Analysis & Interactive Visualizer
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.
- The first element forms a trivially-sorted prefix of length 1.
- Pick the next element as the key.
- Compare against elements in the sorted prefix from right to left, shifting any that are greater than the key.
- 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
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.
Related reading
Sleep Sort: Mechanism, Complexity Analysis & Interactive Visualizer
A unique concurrency-based sorting algorithm: spawns a separate thread for each element, sleeping for a duration proportional to the element value before writing it to the output.
By Md. Harun-Or-Roshid
Cube Sort: Mechanism, Complexity Analysis & Interactive Visualizer
A parallel dimension sorting algorithm: organizes elements in a 3D coordinate cube and sorts vectors along the height, width, and depth axes sequentially to achieve sorted order.
By Md. Harun-Or-Roshid
Patience Sort: Mechanism, Complexity Analysis & Interactive Visualizer
A card-game inspired sorting algorithm: distributes elements onto a series of piles such that each pile's top is \(\ge\) the incoming value, then performs a multi-way merge across pile tops.
By Md. Harun-Or-Roshid
Library Sort: Mechanism, Complexity Analysis & Interactive Visualizer
A gapped variation of Insertion Sort: leaves empty slots (gaps) in the array, allowing elements to be inserted in \(O(1)\) shift time on average by avoiding massive shifts.
By Md. Harun-Or-Roshid