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
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
Key = 5 (index 2)
7 ≥ 5 → shift → [3, 7, 7]; now 3 < 5 → stop. Drop 5 into the gap → [3, 5, 7].
- 3
Result
3 comparisons, 3 shifts. Note the vocabulary: insertion sort SHIFTS (single writes), bubble sort SWAPS (double writes), shifting is cheaper.
Implementation
// 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 / case | Cost | Notes |
|---|---|---|
| Best case (sorted) | O(n) | one comparison per key, no shifts |
| Nearly sorted | O(n + inversions) | adaptive, few shifts |
| Average & worst (reversed) | O(n²) | every key shifts past everything |
| Space | O(1) | in-place, one held key |
| Stable? | Yes | strict > in the shift test never jumps equal keys |