Overview & Concept
Ternary Search is a divide-and-conquer search algorithm that divides a sorted array into three equal parts using two midpoints: mid1 = low + ⌊(high - low)/3⌋ and mid2 = high - ⌊(high - low)/3⌋. It eliminates two-thirds of the search space in each step, executing in O(log₃ n) time. It is also widely used in continuous optimization to find the extremum of unimodal functions.
How It Works
Dual Midpoints: Divides interval [low, high] into three segments: [low, mid1-1], [mid1+1, mid2-1], [mid2+1, high].
Three-Way Partitioning: Compares target against A[mid1] and A[mid2] to determine which third to discard.
Unimodal Optimization: Also optimizes unimodal mathematical curves where values increase to a peak and then decrease.
Step-by-Step Execution
Asymptotic Complexity Analysis
| Metric | Best Case | Average Case | Worst Case | Space Complexity |
|---|---|---|---|---|
| Complexity Bound | O(1) | O(log₃ n) | O(log₃ n) | O(1) |
| Explanation | Optimal input arrangement minimizing operations. | Expected time for uniformly distributed randomized inputs. | Adversarial degenerate conditions requiring full traversal. | Auxiliary memory allocated beyond original input size. |
Pseudocode & Invariants
procedure ternarySearch(A, target):
low = 0; high = n - 1
while low <= high:
mid1 = low + floor((high - low) / 3)
mid2 = high - floor((high - low) / 3)
if A[mid1] == target: return mid1
if A[mid2] == target: return mid2
if target < A[mid1]: high = mid1 - 1
else if target > A[mid2]: low = mid2 + 1
else: low = mid1 + 1; high = mid2 - 1
return -1- Trisection Invariant: If target is present, it resides within one of the three segments.
Advantages & Disadvantages
Key Advantages
- •Reduces search space to one-third per iteration.
- •Unbeatable for finding peaks or valleys of continuous unimodal mathematical functions.
Trade-offs & Limitations
- •Requires up to 4 comparisons per step for discrete arrays, making it slower in practice than Binary Search despite log₃ n.
Real-World Applications
Unimodal Function Optimization
Finding the maximum or minimum of unimodal mathematical functions in graphics and game physics.
Decision Guide: When to Use
Ideal Scenarios
- ✓When optimizing unimodal continuous functions.
Consider Alternatives When
- ✕When searching discrete sorted arrays (Binary Search makes fewer total comparisons).
Explore Related Algorithms
Compare trade-offs and complexity across complementary tools in AlgoViz.