Skip to content
Part IA Lent Term

Binary Insertion Sort

Algorithm

Binary Insertion Sort improves the search step of Insertion Sort by using binary search to find the insertion point, rather than a linear backwards scan. The shifting step remains unchanged.

For each jj from 2 to nn:

  1. The prefix A[1j1]A[1 \dots j-1] is sorted.
  2. Perform binary search on A[1j1]A[1 \dots j-1] to find the index kk where A[j]A[j] belongs (the position where all elements before kk are A[j]\le A[j]).
  3. Shift A[kj1]A[k \dots j-1] right by one position.
  4. Insert A[j]A[j] at position kk.

Binary insertion sort: binary search finds insertion point in sorted prefix, then elements shift

Where the Improvement Lies

Standard Insertion Sort uses a linear scan that performs O(j)O(j) comparisons to find the insertion point for element jj. Binary search performs O(logj)O(\log j) comparisons. Over all nn elements, comparisons drop from Θ(n2)\Theta(n^2) to:

j=2nlog2j=log2(n!)=Θ(nlogn)\sum_{j=2}^{n} \log_2 j = \log_2(n!) = \Theta(n \log n)

Where It Does Not Help

The shifting step still moves up to j1j-1 elements on each insertion. In the worst case, every element must be shifted, requiring:

j=2n(j1)=n(n1)2=Θ(n2)\sum_{j=2}^{n} (j-1) = \frac{n(n-1)}{2} = \Theta(n^2)

movements. Since each shift is a write operation, the total time is still dominated by the Θ(n2)\Theta(n^2) shifting cost. The asymptotic running time remains Θ(n2)\Theta(n^2) worst case and average case.

Comparison: Standard vs Binary Insertion

MetricStandard Insertion SortBinary Insertion Sort
ComparisonsΘ(n2)\Theta(n^2)Θ(nlogn)\Theta(n \log n)
Shifts/swapsΘ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)
Overall timeΘ(n2)\Theta(n^2)Θ(n2)\Theta(n^2)
Best caseΘ(n)\Theta(n)Θ(nlogn)\Theta(n \log n) (binary search still costs logj\log j each)

The best case actually becomes worse with binary insertion: even on an already-sorted array, binary search still costs Θ(logj)\Theta(\log j) comparisons per element, totalling Θ(nlogn)\Theta(n \log n), whereas standard Insertion Sort gets Θ(n)\Theta(n).

When Binary Insertion Sort Is Useful

Binary insertion sort helps when:

  1. Comparisons are expensive, and writes are cheap: e.g. sorting strings where each string comparison is costly but copying a pointer (the “shift”) is lightweight.
  2. The data structure supports binary search but not efficient linear scan: e.g. an array where the sorted prefix is conceptually separate from the insertion machinery.

In practice, standard Insertion Sort is usually preferred because its linear scan is cache-friendly and its best case is genuinely linear.

Summary

AspectDetail
Search methodBinary search in sorted prefix
Comparison countΘ(nlogn)\Theta(n \log n)
Shift countΘ(n2)\Theta(n^2) worst case
Overall timeΘ(n2)\Theta(n^2)
Best caseΘ(nlogn)\Theta(n \log n) (worse than standard)
Use caseExpensive comparisons, cheap writes
Compared to standardReduces comparisons but does not improve asymptote