Keep a sorted prefix
For [5, 2, 4], start with [5] sorted. Insert 2 by shifting 5 right: [2, 5, 4]. Then insert 4 by shifting 5 right: [2, 4, 5]. The animation shows the same shifts. Set Array Size, press Randomize Array, then use Next Step or Auto-Run.
If the array is already sorted, each value needs only one comparison with the previous value, so the work is linear. If it is reverse sorted, every new value shifts across the entire sorted prefix, so the work grows quadratically. More generally, insertion sort performs work related to the number of inversions—pairs that appear in the opposite order from the sorted result.
The standard algorithm is in-place and stable when it shifts only values strictly greater than the current item. Equal values keep their original order.
When to use it
Insertion sort is useful for small arrays, nearly sorted data, or as the small-partition method inside a faster hybrid sort. It is often easier than a more complex algorithm when the input is tiny. For large, randomly ordered arrays, use a comparison sort with O(n log n) worst-case or expected time, such as merge sort or heapsort.
Common mistakes with Insertion Sort
- Swapping instead of shifting: repeated swaps do extra writes compared with moving the larger prefix once per step.
- **Using
>= in a stable implementation:** shifting equal values can reverse their relative order. - Assuming best-case behavior on arbitrary data: its efficiency depends on how many values are already near their final position.