Insertion Sort
Algorithm
Insertion Sort is an incremental algorithm: it builds a sorted prefix one element at a time. For each element , find its correct position within the already-sorted prefix , shift larger elements right, and insert.
Steps (1-indexed pseudocode convention):
- For to :
- While and :
Visual Description
The algorithm maintains two regions: is sorted, is yet to be processed. At each step, peel off , walk backwards through the sorted region shifting any larger element right by one position, then drop the key into the gap.
Correctness
Loop invariant: At the start of each FOR iteration, consists of the original first elements in sorted order.
- Initialisation (): is a single element, trivially sorted.
- Maintenance: The WHILE loop shifts all elements greater than
Keyright by one, preserving sortedness; insertingKeyat the correct position extends the sorted prefix by one. - Termination (): The entire array is sorted.
Complexity Analysis
The running time depends on , the number of WHILE-loop iterations for each :
Best Case:
Input already sorted. for all (only the failing comparison, no shifts). .
Worst Case:
Input reverse-sorted. (shift all previous elements). The comparison count alone is:
Average Case:
On a random permutation, each element moves past roughly half the sorted prefix. The quadratic term carries a factor of but remains .
Properties
| Property | Value |
|---|---|
| In-place | Yes, extra space |
| Stable | Yes, equal keys stay in original relative order |
| Adaptive | Efficient on nearly-sorted data (approaches ) |
| Online | Can sort items as they arrive |
When to Use
Insertion Sort outperforms algorithms for small (roughly ) due to low constant factors and excellent cache locality. It is also ideal for nearly-sorted data or as the base case inside recursive sorts (e.g. switching to Insertion Sort when subarrays fall below a threshold).
Summary
| Aspect | Detail |
|---|---|
| Strategy | Incremental, build sorted prefix |
| Invariant | is sorted |
| Best case | , already sorted |
| Worst case | , reverse-sorted |
| Average case | |
| Comparisons worst | |
| In-place | Yes |
| Stable | Yes |