Binary Search vs Ternary Search
Across our 4 test inputs, Binary Search needed 17 comparisons in total versus 28 for Ternary Search. On average Binary Search runs in O(log n) time and Ternary Search in O(log₃ n). Binary Search is stable; Ternary Search is not.
Head-to-head on identical inputs (comparisons)
| Input | Binary Search | Ternary Search |
|---|---|---|
| Target is first | 4 | 7 |
| Target in the middle | 4 | 5 |
| Target is last | 5 | 7 |
| Target absent | 4 | 9 |
Complexity
| Binary Search | Ternary Search | |
|---|---|---|
| Average time | O(log n) | O(log₃ n) |
| Worst time | O(log n) | O(log₃ n) |
| Space | O(1) | O(1) |
| Stable | Yes | No |
When to use Binary Search
Sorted arrays when O(log n) search time is needed. Foundation for many advanced algorithms.
When to use Ternary Search
Finding the peak/valley of a unimodal function; for plain sorted lookups binary search is usually better.