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 from 2 to :
- The prefix is sorted.
- Perform binary search on to find the index where belongs (the position where all elements before are ).
- Shift right by one position.
- Insert at position .
Where the Improvement Lies
Standard Insertion Sort uses a linear scan that performs comparisons to find the insertion point for element . Binary search performs comparisons. Over all elements, comparisons drop from to:
Where It Does Not Help
The shifting step still moves up to elements on each insertion. In the worst case, every element must be shifted, requiring:
movements. Since each shift is a write operation, the total time is still dominated by the shifting cost. The asymptotic running time remains worst case and average case.
Comparison: Standard vs Binary Insertion
| Metric | Standard Insertion Sort | Binary Insertion Sort |
|---|---|---|
| Comparisons | ||
| Shifts/swaps | ||
| Overall time | ||
| Best case | (binary search still costs each) |
The best case actually becomes worse with binary insertion: even on an already-sorted array, binary search still costs comparisons per element, totalling , whereas standard Insertion Sort gets .
When Binary Insertion Sort Is Useful
Binary insertion sort helps when:
- 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.
- 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
| Aspect | Detail |
|---|---|
| Search method | Binary search in sorted prefix |
| Comparison count | |
| Shift count | worst case |
| Overall time | |
| Best case | (worse than standard) |
| Use case | Expensive comparisons, cheap writes |
| Compared to standard | Reduces comparisons but does not improve asymptote |