What's happening?
- The first value on its own counts as sorted.
- Each next value is "picked up" and compared with the sorted values to its left; bigger ones shift right to make room.
- When a smaller (or equal) value is reached, the picked-up value drops into the gap.
Complexity
- Time
- O(n²) worst and average · O(n) when already nearly sorted
- Space
- O(1) — sorts in place
Where you'll meet it
Small or nearly-sorted data. Real libraries (Java's and Python's sorts, TimSort) switch to insertion sort for short runs because it is so fast there.
Common mistake
Assuming it is always slow. On nearly sorted input it does almost no work — often beating "faster" algorithms.
FAQ
Is insertion sort stable?
Yes. Equal values never pass each other, so their original order is kept.
Why is it fast on nearly sorted data?
Each value only moves as far as it is out of place. If nothing is far out of place, there is little to shift.
Insertion sort vs bubble sort?
Both are O(n²), but insertion sort usually does far fewer moves and is preferred in practice.