/utils

Binary Insertion Sort

Insertion sort that finds each key's slot with binary search. It needs about n log n comparisons, but it still shifts up to n²/2 values.

SolvesSorting

best
O(n log n)
average
O(n^2)
worst
O(n^2)
space
O(1)

Insertion sort looks for the slot of each key with a linear scan. The prefix is already sorted, so binary search can find the slot with far fewer comparisons.

Already sorted: each search ends at the end of the prefix, so no key moves. There are no shifts, but still about log₂ i comparisons per key: O(n log n).

1021i324354657687

key = none

1def binary_insertion_sort(a):2    for i in range(1, len(a)):3        key = a[i]4        low = 05        high = i6        # first value in a[0..i) larger than key7        while low < high:8            mid = (low + high) // 29            if a[mid] > key:10                high = mid11            else:12                low = mid + 113        # shift a[low..i) one slot right14        for j in range(i, low, -1):15            a[j] = a[j - 1]16        a[low] = key17    return a
1 / 61

a[0..0] is sorted; next element is a[1].

comparisons
0
shifts
0

How it works

The array is split into a sorted prefix a[0..i) and the unsorted rest. Each round:

  1. Take key = a[i].
  2. Binary search the prefix for the first value that is larger than key. Call its index low.
  3. Shift a[low..i) one slot to the right.
  4. Write key into a[low].

Searching for the first value that is larger than key puts key behind its equal values. This keeps the sort stable [1].

Complexity

CaseInputComparisonsShiftsTime
Bestsorted≈nlog⁡2n\approx n \log_2 n00O(nlog⁡n)O(n \log n)
Averagerandom≈nlog⁡2n\approx n \log_2 n≈n2/4\approx n^2/4O(n2)O(n^2)
Worstreverse sorted≈nlog⁡2n\approx n \log_2 nn(n−1)2\frac{n(n-1)}{2}O(n2)O(n^2)

The search for a prefix of length ii needs at most ⌈log⁡2(i+1)⌉\lceil \log_2 (i + 1) \rceil comparisons. The shifts are unchanged: they still cost one write per inversion. So the running time stays O(n2)O(n^2) on random input.

Implementations

  • Standard: binary search for the slot, then a block shift.

Pitfalls

  • Sorted input is no longer the cheapest case in comparisons. Plain insertion sort needs n−1n - 1 comparisons there, binary insertion about nlog⁡2nn \log_2 n.
  • With a linked list the shift is cheap, but the binary search needs random access. The idea works for arrays only.

Related

References

  1. D. E. Knuth, The Art of Computer Programming, Volume 3: Sorting and Searching, 2nd ed., Addison-Wesley, 1998.

Further reading

  • K. Mehlhorn and P. Sanders, Algorithms and Data Structures: The Basic Toolbox, Springer, 2008.

Full bibliography