DSA Notes
Master ternary search — what it is, why it differs from binary search, how to find the maximum or minimum of a unimodal function in O(log n), ternary search on sorted arrays vs functions, comparison with binary search, and classic applications.
What Is Ternary Search?
Ternary search is a divide-and-conquer algorithm that finds the maximum or minimum of a unimodal function — a function that first increases (or decreases) monotonically, reaches a single peak (or valley), and then decreases (or increases) monotonically.
Unlike binary search which finds a specific value in a sorted array, ternary search finds the *extreme point* of a unimodal function. It divides the search range into three parts at each step.
The Ternary Search Algorithm
Divide the range into three equal parts using two midpoints m1 and m2:
| If f(m1) < f(m2): maximum is in [m1, right] | left = m1 |
| If f(m1) > f(m2): maximum is in [left, m2] | right = m2 |
| If f(m1) == f(m2): maximum is in [m1, m2] | shrink both ends |
Implementation — Find Maximum on Sorted Array
Implementation — Find Maximum of Continuous Function
Ternary Search vs Binary Search
| Feature | Binary Search | Ternary Search |
|---|---|---|
| Purpose | Find specific value | Find maximum/minimum |
| Data requirement | Sorted array | Unimodal function |
| Steps per iteration | 1 comparison | 2 comparisons |
| Reduction per step | Eliminates 1/2 | Eliminates 1/3 |
| Complexity | O(log₂ n) | O(log₁.₅ n) ≈ O(log n) |
| When to use | Known sorted array | Unimodal optimization |
Why not divide into more parts? The more divisions, the more comparisons per step. Binary search with 1 comparison eliminating 1/2 is optimal for sorted array search. Ternary search makes 2 comparisons to eliminate 1/3 — the same total work per "elimination ratio" as binary search.
Classic Application — Optimal Point in Geometry
Ternary Search in Competitive Programming
Common CP problems using ternary search:
Number of Iterations
Ternary search reduces the range to 2/3 each step:
Summary
- Ternary search finds the maximum or minimum of a unimodal function
- Divides range into thirds using two probes m1 and m2
- Eliminates one-third of the range per iteration → O(log n) total
- Requires: Strictly unimodal function on the search range
- Use when: Optimizing over a continuous or discrete domain with a single peak/valley
- For sorted array value search → use binary search instead
*Next Lesson: Search Comparison*
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Ternary Search — Finding Maximum/Minimum of Unimodal Functions.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Data Structures & Algorithms topic.
Search Terms
data-structures-algorithms, data structures & algorithms, data, structures, algorithms, searching, ternary, search
Related Data Structures & Algorithms Topics