Insertion sort is how many people sort a hand of cards: keep the cards you've already looked at in order, and slide each new card into its place among them.
sorted the sorted part so far key the value being inserted ? not looked at yet done all sorted
Every shift moves one value past the key, fixing one inversion: a pair of values in the wrong order. So the number of shifts is exactly the number of inversions. A sorted array has none, so insertion sort runs in linear time; a reversed one has the most, n(n − 1)/2.
| Insertion sort | |
|---|---|
| Best time | O(n), on input that's already sorted |
| Worst and average time | O(n²) |
| Extra space | O(1): in place |
| Stable? | Yes: a value only moves past larger ones |
For small or nearly sorted arrays it beats the O(n log n) sorts, which is why real libraries switch to it for short pieces inside quicksort and merge sort.