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).
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 aa[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:
- Take
key = a[i]. - Binary search the prefix for the first value that is larger than
key. Call its indexlow. - Shift
a[low..i)one slot to the right. - Write
keyintoa[low].
Searching for the first value that is larger than key puts key behind its equal values.
This keeps the sort stable [1].
Complexity
| Case | Input | Comparisons | Shifts | Time |
|---|---|---|---|---|
| Best | sorted | |||
| Average | random | |||
| Worst | reverse sorted |
The search for a prefix of length needs at most comparisons. The shifts are unchanged: they still cost one write per inversion. So the running time stays 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 comparisons there, binary insertion about .
- With a linked list the shift is cheap, but the binary search needs random access. The idea works for arrays only.
Related
References
- 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.