Sub topic 11
Binary Insertion Sort: Fewer Comparisons, Same Number of Moves
This chapter assumes you already know plain insertion sort and its invariant. That invariant says the prefix a[:i] is sorted before step i. It also assumes you know the cost model that counts comparisons and moves separately, the idea of stability, and how inversions relate to insertion sort's shifts. You should also be comfortable with binary search and Big-O notation.
Plain insertion sort finds where a new element belongs by walking left through the sorted prefix, one comparison at a time. The prefix is already sorted, so a binary search could find that position much faster. Binary insertion sort makes that change. The result shows clearly why the cost model keeps comparisons and moves apart: binary search reduces one of them and leaves the other unchanged.
The idea: search, then shift
Each step of insertion sort does two jobs:
- Locate the position where
key = a[i]belongs in the sorted prefixa[:i]. - Make room by moving every prefix element that is greater than
keyone slot to the right, then writekeyinto the gap.
Plain insertion sort does both jobs in one loop, comparing and shifting as it goes. Binary insertion sort separates them. It finds the position with a binary search over a[0:i], then moves the block a[pos:i] right by one position as a single operation.
Implementation with `bisect`
Python's standard bisect module provides the search. bisect.bisect_right(a, x, lo, hi) returns the index where x would go in the sorted slice a[lo:hi], placed after any elements equal to x.
import bisect
def binary_insertion_sort(a):
for i in range(1, len(a)):
key = a[i]
# bisect_right places key after equal elements, preserving stability.
pos = bisect.bisect_right(a, key, 0, i)
a[pos + 1:i + 1] = a[pos:i]
a[pos] = key
return a
print(binary_insertion_sort([4, 2, 7, 1, 3, 2])) # [1, 2, 2, 3, 4, 7]The slice assignment a[pos + 1:i + 1] = a[pos:i] does the shifting. The right-hand side makes a copy first, so the overlapping regions do not corrupt each other. Both slices have length i - pos, so the list keeps its length. That line overwrites a[i], which is why key is saved before the shift.
The invariant has the same structure as in plain insertion sort. Before iteration i, a[:i] holds the original first i elements in sorted order. Binary search returns a position pos where everything in a[:pos] is <= key and everything in a[pos:i] is > key. After the shift and the write, a[:i+1] is sorted and holds the original first i + 1 elements, so the invariant holds at the next iteration.
Counting comparisons and moves
To see the trade-off, instrument both algorithms. The binary search below is written by hand so that each comparison can be counted. It has the same semantics as bisect_right: a key equal to a[mid] sends the search right.
def insertion_counts(a):
a = list(a)
comps = moves = 0
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0:
comps += 1
if a[j] > key:
a[j + 1] = a[j]
moves += 1
j -= 1
else:
break
a[j + 1] = key
return a, comps, moves
def binary_insertion_counts(a):
a = list(a)
comps = moves = 0
for i in range(1, len(a)):
key = a[i]
lo, hi = 0, i
while lo < hi:
mid = (lo + hi) // 2
comps += 1
if key < a[mid]:
hi = mid
else:
lo = mid + 1
moves += i - lo
a[lo + 1:i + 1] = a[lo:i]
a[lo] = key
return a, comps, moves
for name, data in [("sorted", list(range(8))),
("reversed", list(range(7, -1, -1)))]:
print(name, insertion_counts(data)[1:], binary_insertion_counts(data)[1:])
# sorted (7, 0) (13, 0)
# reversed (28, 28) (17, 28)Each tuple is (comparisons, moves):
| Input (n = 8) | Plain insertion | Binary insertion |
|---|---|---|
| Already sorted | 7 comparisons, 0 moves | 13 comparisons, 0 moves |
| Reversed | 28 comparisons, 28 moves | 17 comparisons, 28 moves |
Two facts follow from this table.
First, the moves are identical on every input. The number of elements that must shift right to make room for key is the number of prefix elements greater than key. Binary search does not change that number. Summed over all steps, it equals the number of inversions in the input, which is the same count plain insertion sort shifts. On reversed input that is n(n−1)/2 = 28.
Second, comparisons improve in the worst case and get worse in the best case. On sorted input, plain insertion sort makes one comparison per step, finds a[i-1] <= key, and stops. Binary search does not take advantage of that. It still uses about log₂ i comparisons on every step, even when the answer is "stay where you are."
Asymptotic costs
For a prefix of length i, binary search makes at most ⌈log₂(i + 1)⌉ comparisons. Summing over all steps gives the worst-case total:
- Comparisons: the sum of ⌈log₂ k⌉ for k = 2 to n, which is about n log₂ n − 1.44n. That is close to log₂(n!), the lower bound on comparisons for any comparison sort. For n = 8 the sum is 1+2+2+3+3+3+3 = 17, which matches the reversed-input measurement above.
- Moves: Θ(n²) in the worst and average case, because the average input has about n(n−1)/4 inversions.
- Extra space: O(1) in principle. The Python slice copy above uses O(i) temporary space. An in-place version would move elements right to left in a loop, or use a
memmovein a lower-level language.
| Case | Plain insertion comparisons | Binary insertion comparisons | Moves (both) |
|---|---|---|---|
| Best (sorted) | n − 1 | Θ(n log n) | 0 |
| Average | ~n²/4 | Θ(n log n) | ~n²/4 |
| Worst (reversed) | n(n−1)/2 | Θ(n log n) | n(n−1)/2 |
The overall running time is still Θ(n²) in the average and worst cases, because the moves dominate. Binary insertion sort is not an O(n log n) sort. It is an O(n log n)-comparison sort that remains quadratic overall.
Stability depends on which bisect you use
Plain insertion sort is stable because it uses a strict > test. It stops shifting when it reaches an element equal to key, so key ends up after its equal-keyed predecessors. Binary insertion sort keeps this property only if the search returns the rightmost valid position, which is bisect_right.
If you use bisect_left instead, key lands before any earlier elements with an equal key. Records that compare equal would then change their original order, and the sort would be unstable. The two functions give the same result on plain integers, because equal integers cannot be told apart. The difference appears only when sorting records by a key. A test suite that only sorts lists of int will not catch the bug.
Since Python 3.10, bisect functions accept a key= argument. The value you search for must already be a key, not a whole record:
import bisect
def binary_insertion_sort_by(a, key):
for i in range(1, len(a)):
item = a[i]
pos = bisect.bisect_right(a, key(item), 0, i, key=key)
a[pos + 1:i + 1] = a[pos:i]
a[pos] = item
return a
records = [(2, 'a'), (1, 'x'), (2, 'b'), (1, 'y')]
print(binary_insertion_sort_by(records, key=lambda r: r[0]))
# [(1, 'x'), (1, 'y'), (2, 'a'), (2, 'b')]When the trade is worth it
Binary insertion sort is worth using when a comparison costs much more than a move. Typical cases:
- Expensive comparisons. Comparing long strings with shared prefixes, tuples of many fields, or objects with a user-defined
__lt__in an interpreted language. In CPython, each comparison of objects is a dynamic method call, while shifting a block of list slots is a singlememmoveof pointers. Reducing comparisons from quadratic to n log n can outweigh the Θ(n²) pointer moves for small n. - Contiguous arrays of references or small values. Moving a block of adjacent slots is a tight, cache-friendly copy. In practice its constant factor is far lower than the same number of separate shift-and-compare steps.
It does not help in these cases:
- Linked lists. Binary search needs random access by index. On a linked list, reaching the middle costs O(i), so you lose the advantage. Moving a node is O(1) there, so plain linear insertion is the natural fit.
- Large records stored by value. If each move copies a large struct, moves dominate and binary search reduces the cheaper cost.
- Nearly sorted input with cheap keys. As shown above, plain insertion sort makes fewer comparisons here.
Common mistakes
- Searching the whole array. The search range must be
0toi. Includinga[i]or any element after it searches unsorted data and returns wrong positions. - Forgetting to save
key. The shift overwritesa[i]. Read it into a variable before moving anything. - Using
bisect_leftfor records. This breaks stability, as described above. - Claiming O(n log n) overall. Only the comparisons are O(n log n). The moves keep the running time quadratic.
- Using
bisect.insorton a separate list.insortgives the same costs, but if you build a new list you no longer have an in-place sort, and you use O(n) extra space.
Exercise
For n = 16 and reversed input, how many comparisons do plain insertion sort and binary insertion sort make, and how many moves does each perform?
Show answer
Plain insertion sort makes n(n−1)/2 = 120 comparisons. Binary insertion sort makes the sum of ⌈log₂ k⌉ for k = 2..16, which is 1 + 2·2 + 4·3 + 8·4 = 49 comparisons. Both perform 120 moves, because reversed input has 120 inversions and each inversion costs one shift.
Exercise
Replace bisectright with bisectleft in binaryinsertionsort_by and sort [(2, 'a'), (2, 'b')] by the first field. What is the result, and why?
Show answer
The result is [(2, 'b'), (2, 'a')]. At i = 1 the key is 2. bisect_left returns position 0, before the equal-keyed (2, 'a'), so (2, 'b') moves ahead of it. The relative order of equal keys flips, so the sort is unstable.
Exercise
You need to sort lists of about 30 records that are usually already in order, and comparing two records is cheap (one integer field). Should you use plain or binary insertion sort?
Show answer
Use plain insertion sort. On nearly sorted input it makes about n comparisons and few moves. Binary insertion sort would still spend about log₂ i comparisons per element without reducing moves, and with cheap comparisons its only advantage disappears.