Ternary Search¶
We are given a function
-
The function strictly increases first, reaches a maximum (at a single point or over an interval), and then strictly decreases.
-
The function strictly decreases first, reaches a minimum, and then strictly increases.
In this article, we will assume the first scenario. The second scenario is completely symmetrical to the first.
The task is to find the maximum of function
Algorithm¶
Consider any 2 points
-
The desired maximum can not be located on the left side of
-
This situation is symmetrical to the previous one: the maximum can not be located on the right side of
-
We can see that either both of these points belong to the area where the value of the function is maximized, or
Thus, based on the comparison of the values in the two inner points, we can replace the current interval
We didn't impose any restrictions on the choice of points
If
Run time analysis¶
It can be visualized as follows: every time after evaluating the function at points
Applying Master's Theorem, we get the desired complexity estimate.
The case of the integer arguments¶
If
The difference occurs in the stopping criterion of the algorithm. Ternary search will have to stop when
Golden section search¶
In some cases computing
To see how to do this, let's revisit the selection method for
Now suppose that after the current iteration we set
Multiplying both sides of
This is a well-known golden section equation. Solving it yields
Implementation¶
double ternary_search(double l, double r) {
double eps = 1e-9; //set the error limit here
while (r - l > eps) {
double m1 = l + (r - l) / 3;
double m2 = r - (r - l) / 3;
double f1 = f(m1); //evaluates the function at m1
double f2 = f(m2); //evaluates the function at m2
if (f1 < f2)
l = m1;
else
r = m2;
}
return f(l); //return the maximum of f(x) in [l, r]
}
Here eps
is in fact the absolute error (not taking into account errors due to the inaccurate calculation of the function).
Instead of the criterion r - l > eps
, we can select a constant number of iterations as a stopping criterion. The number of iterations should be chosen to ensure the required accuracy. Typically, in most programming challenges the error limit is
Practice Problems¶
- Codeforces - New Bakery
- Codechef - Race time
- Hackerearth - Rescuer
- Spoj - Building Construction
- Codeforces - Weakness and Poorness
- LOJ - Closest Distance
- GYM - Dome of Circus (D)
- UVA - Galactic Taxes
- GYM - Chasing the Cheetahs (A)
- UVA - 12197 - Trick or Treat
- SPOJ - Building Construction
- Codeforces - Devu and his Brother
- Codechef - Is This JEE
- Codeforces - Restorer Distance
- TIMUS 1058 Chocolate
- TIMUS 1436 Billboard
- TIMUS 1451 Beerhouse Tale
- TIMUS 1719 Kill the Shaitan-Boss
- TIMUS 1913 Titan Ruins: Alignment of Forces