AlgoLab

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

Starting binary insertion sort on an array of 20 items.

Starting binary insertion sort on an array of 20 items.
  1. 1for each position from the second item to the last, remember its value as the one being inserted
  2. 2binary search the already-sorted portion to its left for the position where it belongs
  3. 3compare the remembered value with the value at the midpoint of the current search range
  4. 4narrow the search range to the half that could still contain the insertion point
  5. 5once the search range is empty, shift every value from the insertion point to the current position one place to the right
  6. 6place the remembered value into the gap the shifting left behind
  7. 7the array is fully sorted
Comparisons
0
Writes
0
Accesses
0

Complexity

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

Binary insertion sort

Binary insertion sort is ordinary insertion sort with one change: instead of scanning left from the current position to find where a value belongs, it binary searches the already-sorted prefix for that position. Once the position is found, it still has to shift every value between that point and the current position one place right to make room, exactly as plain insertion sort does.

When it is the right choice

It is worth using over plain insertion sort specifically when comparisons are expensive relative to moving values — comparing long strings or calling a costly comparator function, for instance — since it cuts comparisons from O(n) to O(log n) per insertion. It buys nothing when comparisons are cheap: the shifting that dominates insertion sort's cost on large or reversed arrays is exactly as expensive here, so its worst-case running time is still O(n²).

How it works

Worth noticing

Cost

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

Worth comparing

All algorithms