Already sorted: one comparison per key and no shifts, Θ(n).
Sorting algorithms · 1/7
Insertion sort
Builds a sorted prefix one item at a time.
How it works
Extract the current key, shift larger prefix values right, then insert the key into the gap.
Step-by-step visualization
Each bar represents one element. Colors identify compared elements, the pivot or key, the final region and the active range.
Use 2 to 16 values. This visualizer accepts values from 0 to 999.
- Comparisons
- 0
- Writes
- 0
- Swaps
- 0
- Pass / level
- 0
Pseudocode linked to the visualization
for i ← 1 to n − 1key ← A[i]j ← i − 1while j ≥ 0 and A[j] > keyA[j + 1] ← A[j]j ← j − 1A[j + 1] ← key
The highlighted line corresponds to the operation described by the visualizer. Index-management details are intentionally simplified.
Complexity analysis
A key crosses a linear fraction of the prefix on average, Θ(n²).
Reverse order causes n(n−1)/2 shifts, Θ(n²).
Only a key and indices are stored: Θ(1). Strict > comparisons preserve stability.
Properties at a glance
Stability concerns the relative order of elements with equal keys.
This classification refers to the version shown on this page.
When to use it and what to avoid
A good choice when…
Excellent for small or nearly sorted arrays and as the finishing stage in hybrids.
Common mistake
Using ≥ instead of > can reverse equal elements and lose stability.