Insertion Sort
- Ω( n )
- Θ( n2 )
- O( n2 )
- space O( 1 )
Insertion sort treats the left part of the array as already sorted and takes the next element as a key. It lifts the key out, slides every larger value one cell to the right, and drops the key into the gap that opens. The work is the number of pairs that are out of order, so a nearly sorted array is nearly free while a reversed one is the worst case. That sensitivity to the input is the algorithm's defining trait.
- Comparisons count only element-against-element checks; loop and index checks are never counted.
- Reads and writes include reads and writes to helper buffers (merge, counting, radix, bucket and tim sort).
- A swap counts once, as a swap. It is never also counted as a read or a write.
- Real time is the average time of the counted sort on this device over repeated runs, measured once before playback and independent of animation speed. Visual time is the time spent animating, excluding pauses.
How insertion sort works
On 5, 2, 6, 1, 4, 3 the sorted prefix starts as just the 5. The key 2 is smaller, so the 5 is copied one cell right, [5, 5, 6, 1, 4, 3], and the key is written into the gap at index 0: [2, 5, 6, 1, 4, 3]. The 6 is not smaller than the 5, so it stays where it is, with one comparison and no write at all. Notice the duplicated 5 in the middle step; the key is held in a variable, so the array briefly contains a stale copy.
The key 1 is the expensive one. It is smaller than 6, 5 and 2, so those three shift right one by one, giving [2, 5, 6, 6, 4, 3], then [2, 5, 5, 6, 4, 3], then [2, 2, 5, 6, 4, 3], and the 1 is written at index 0 for [1, 2, 5, 6, 4, 3]. The key 4 shifts the 6 and the 5, stops at the 2, and lands at index 2: [1, 2, 4, 5, 6, 3]. The last key, the 3, moves past 6, 5 and 4, passing through [1, 2, 4, 5, 6, 6], [1, 2, 4, 5, 5, 6] and [1, 2, 4, 4, 5, 6] before it is written at index 2.
The totals are 12 comparisons and 13 writes, with no swaps. Nine of the writes are shifts, one for each pair that was out of order, and four are the key writes. A version that swapped neighbours instead of holding a key would perform the same nine exchanges, each writing two cells, so 18 writes. Holding the key is what keeps the count lower.
| Step | Change | Array after |
|---|---|---|
| 1 | Write 5 at index 1 | 5 5 6 1 4 3 |
| 2 | Write 2 at index 0 | 2 5 6 1 4 3 |
| 3 | Write 6 at index 3 | 2 5 6 6 4 3 |
| 4 | Write 5 at index 2 | 2 5 5 6 4 3 |
| 5 | Write 2 at index 1 | 2 2 5 6 4 3 |
| 6 | Write 1 at index 0 | 1 2 5 6 4 3 |
| 7 | Write 6 at index 4 | 1 2 5 6 6 3 |
| 8 | Write 5 at index 3 | 1 2 5 5 6 3 |
| 9 | Write 4 at index 2 | 1 2 4 5 6 3 |
| 10 | Write 6 at index 5 | 1 2 4 5 6 6 |
| 11 | Write 5 at index 4 | 1 2 4 5 5 6 |
| 12 | Write 4 at index 3 | 1 2 4 4 5 6 |
12 of 13 changes shown; the rest follow the same pattern until the array is sorted.
Pseudocode
for i = 1 to n - 1
key = a[i]
j = i - 1
while j >= 0 and key < a[j]
a[j + 1] = a[j]
j = j - 1
a[j + 1] = key
Why these complexities
The cost is governed by inversions, the pairs in which a larger value comes before a smaller one. Every shift removes exactly one inversion, and every key costs at most one extra comparison to find where it stops. Comparisons are therefore the number of inversions plus at most n - 1. Sorted input has none, so it takes n - 1 comparisons and no writes: seven comparisons for eight elements, which is the O(n) best case.
Reversed input has the maximum, n(n-1)/2 inversions, which means n(n-1)/2 comparisons and as many shifts, plus a key write per element. For eight elements that is 28 comparisons and 35 writes. On random data half of all pairs are inverted, so the average is about n²/4 shifts and about n²/4 comparisons. It remains O(n²), but with a smaller constant than bubble sort or selection sort. If every element starts at most d cells from its final place, the work is about n times d, which is why nearly sorted data is fast.
Space is O(1), one key variable plus indices. The loop condition uses a strict less-than, so a key stops as soon as the value before it is equal, and equal values never cross each other. The implementation also skips the final write when the key did not move, which is why an element already in place causes no write. Because the prefix is always sorted, the method can take elements as they arrive from a stream.
Measured on this site
Exact counts from this site's own engine for 32 elements, using the same rules as the visualiser.
| Input | Comparisons | Writes | Swaps |
|---|---|---|---|
| Random | 338 | 341 | 0 |
| Already sorted | 31 | 0 | 0 |
| Reversed | 496 | 527 | 0 |
| Few distinct values | 200 | 191 | 0 |
When to use it
Use it for small arrays and for data that is already nearly sorted, where it runs close to linear time. Many fast sorts, such as tim sort and intro sort, use it for their small pieces.
Frequently asked questions
Why is insertion sort good on nearly sorted data?
Each element only moves past the few larger elements before it, so the work is proportional to the number of out-of-order pairs.
Is insertion sort stable?
Yes. An element stops moving left when the one before it is not larger.
Does it sort in place?
Yes. It needs a constant amount of extra memory, and it can sort data as it arrives.
Would a binary search for the position make insertion sort faster?
It cuts the comparisons to about n log₂ n in total, but the shifting stays. In an array, making room for the key still means moving every larger value one cell, so the worst case remains O(n²) writes. The gain matters only when a comparison is far more expensive than a move, for example when comparing long strings, and binary insertion also loses the early exit that makes sorted input linear.
Why does the trace show duplicate values partway through a move?
The key is held in a variable while larger values shift right, and each shift copies a value over the cell to its right. For a moment the array has two copies of the shifted value, as in [2, 5, 5, 6, 4, 3], until the key is written into the gap. Nothing is lost, since the key is safe in the variable, and the final write removes the stale copy.
Background
No inventor is named for insertion sort. It is the way most people sort a hand of playing cards, picking up one card at a time and sliding it into place among the ones already held, and it was one of the earliest methods described for computers. Knuth analyses it in section 5.2.1 of volume 3, and notes that binary insertion was already mentioned in the 1940s in some of the first published discussions of sorting on machines.
Its modern importance is as a component. Shell sort generalises it by letting elements shift across gaps, and hybrid algorithms such as tim sort and intro sort fall back to it for short ranges, where its tiny constant factor and lack of overhead beat the recursive methods. Many standard-library sorts therefore run insertion sort on thousands of small slices of a large array.
References
- Knuth, The Art of Computer Programming, vol. 3, section 5.2.1 (Sorting by Insertion)
- Cormen, Leiserson, Rivest, Stein, Introduction to Algorithms, section 2.1 (Insertion sort)
- Sedgewick and Wayne, Algorithms, 4th edition, section 2.1 (Elementary Sorts)
Compare with
| Algorithm | Average time | Worst time |
|---|---|---|
| Shell Sort | Θ( n4/3 ) | O( n2 ) |
| Best time | Ω( n ) | good |
|---|---|---|
| Average time | Θ( n2 ) | poor |
| Worst time | O( n2 ) | poor |
| Worst space | O( 1 ) | good |
Properties
- Stable
- Yes
- In place
- Yes
- Adaptive
- Yes
- Comparison-based
- Yes