AlgoLab

O(n²)·O(1) space·stable
645559896316373459948511843281951114277

Starting insertion sort on an array of 20 items.

Starting insertion sort on an array of 20 items.
  1. 1for each position from the second item to the last
  2. 2remember this value as the one being inserted
  3. 3compare the remembered value with the value to its left
  4. 4if the value to the left is greater, shift it one position right
  5. 5place the remembered value into the gap the shifting left behind
  6. 6the array is fully sorted
Comparisons
0
Writes
0
Accesses
0

Complexity

BestO(n)
AverageO(n²)
WorstO(n²)
Extra spaceO(1)
StableYes
n² at n=20 predicts 400; this run took 0.

Insertion sort

Insertion sort grows a sorted prefix one value at a time: it takes the next value, shifts every larger value already in the sorted prefix one place to the right, then drops the new value into the gap left behind.

When it is the right choice

Insertion sort is a strong choice for small arrays and for data that is already nearly sorted, where its running time approaches O(n). It is also the base case many real merge sort implementations switch to below a small threshold, since its low overhead beats merge sort's recursion for tiny ranges. It is a poor choice for large, randomly ordered arrays, where it degrades to O(n²).

How it works

Worth noticing

Cost

Best
O(n)
Average
O(n²)
Worst
O(n²)
Extra space
O(1)
Stable
Yes

Worth comparing

All algorithms