Sub topic 11
Binary Insertion Sort: Fewer Comparisons, Same Number of Moves
This chapter assumes you already know plain insertion sort, Big-O notation, and the cost model from earlier chapters, which counts comparisons and element moves separately. It also assumes you know Python's bisect module, or at least the idea of binary search on a sorted list.
The idea
Plain insertion sort finds the insertion point for a[i] by walking left through the sorted prefix a[:i]. It compares the key with each element and shifts that element as it goes. In the worst case, step i costs i comparisons and i shifts.
The prefix a[:i] is already sorted, so binary search can find the insertion point in about log₂(i) comparisons. That is binary insertion sort. Finding the position becomes cheap. Opening a gap still means moving every element between the insertion point and position i one slot to the right, and binary search cannot reduce that.
The implementation
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] performs the shift. Python copies the right-hand slice before it writes, so the overlapping ranges are handled correctly. The loop invariant is the same as in plain insertion sort: before step i, a[:i] holds the original first i elements in sorted order.
Measuring the difference
The program below counts comparisons and moves for both versions on a reversed list of 8 elements, which is the worst case.
def linear_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 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: # hand-written bisect_right so we can count
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 comps, moves
data = list(range(8, 0, -1))
print("linear:", linear_insertion_counts(data)) # linear: (28, 28)
print("binary:", binary_insertion_counts(data)) # binary: (17, 28)The comparison count falls from 28 to 17, and the move count stays at 28. As n grows, comparisons fall from Θ(n²) to Θ(n log n), and moves stay at Θ(n²) in the worst and average cases.
| Measure | Insertion sort | Binary insertion sort |
|---|---|---|
| Comparisons, worst case | n(n−1)/2 | about n log₂ n |
| Comparisons, sorted input | n − 1 | about n log₂ n |
| Moves, worst case | n(n−1)/2 | n(n−1)/2 |
| Moves, sorted input | 0 | 0 |
| Overall time, worst case | O(n²) | O(n²) |
| Stable | Yes | Yes, with `bisect_right` |
Common errors
Binary search also hurts on input that is already sorted. Plain insertion sort makes one comparison per element on sorted input. The binary version still runs a full binary search at every step, so its best case grows from n − 1 comparisons to about n log n. Binary search removes the adaptivity in comparisons, and only the adaptivity in moves remains.
When it is worth it
Use binary insertion sort when a comparison costs much more than a move. Examples are comparing long strings, calling a Python key function, or comparing objects through a slow __lt__. Moving a block of references is a fast memory copy, and here it happens in C inside the slice assignment. CPython's Timsort uses binary insertion sort to extend short runs for the same reason.
When comparisons are cheap, such as comparing machine integers, plain insertion sort is usually just as fast. On nearly sorted data it is often faster.
Exercise
Binary insertion sort runs on [1, 2, 3, 4, 5, 6, 7, 8] using bisect_right. How many element moves does it make, and is its comparison count higher or lower than plain insertion sort's 7?
Show answer
It makes zero moves, because every insertion point is i, so no element needs to shift. Its comparison count is higher. Each step runs a full binary search over a prefix of size i, giving 1+2+2+3+3+3+3 = 17 comparisons for i = 1 to 7. Plain insertion sort needs only 7.
Exercise
Why is binary insertion sort still O(n²) in the worst case, even though it finds each position in O(log n)?
Show answer
Each insertion still shifts every element between the insertion point and position i. On reversed input that is i moves at step i, for n(n−1)/2 moves in total, and that term dominates the running time.