Linear Search vs Ternary Search
Across our 4 test inputs, Ternary Search needed 28 comparisons in total versus 42 for Linear Search. On average Linear Search runs in O(n) time and Ternary Search in O(log₃ n). Linear Search is stable; Ternary Search is not. Ternary Search only works on sorted data.
Head-to-head on identical inputs (comparisons)
| Input | Linear Search | Ternary Search |
|---|---|---|
| Target is first | 1 | 7 |
| Target in the middle | 9 | 5 |
| Target is last | 16 | 7 |
| Target absent | 16 | 9 |
Complexity
| Linear Search | Ternary Search | |
|---|---|---|
| Average time | O(n) | O(log₃ n) |
| Worst time | O(n) | O(log₃ n) |
| Space | O(1) | O(1) |
| Stable | Yes | No |
When to use Linear Search
Unsorted arrays, small datasets, or when you need to find all occurrences.
When to use Ternary Search
Finding the peak/valley of a unimodal function; for plain sorted lookups binary search is usually better.