Iron_Price's blog

By Iron_Price, history, 4 years ago, In English

Is there anything wrong using this approach for ternary search on integers?

while (R - L >= 3)
{
  m1 = (L+L+R) / 3;
  m2 = (L+R+R) / 3;
  // say we're looking for the maximum
  if(f(m1) > f(m2)) R = m2;
  else if(f(m2) > f(m1)) L = m1;
  else L = m1, R = m2;
}
ans = inf;
for(i = L; i <= R; i++) ans = min(ans, f(i));

This blog shows a different way and tells not to use to approach above. But I don't understand why.

  • Vote: I like it
  • -4
  • Vote: I do not like it

| Write comment?
»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

You can think of the blog approach as looking at the "slope" of the function to determine which side of the extremum it's on (canonical ternary search also does this in a sense when the two points you are querying lie on the same side of the extremum). The blog approach runs in $$$\log_2(N)$$$ iterations instead of $$$\log_{1.5}(N)$$$ iterations since it cuts the search space in half each time.

Note: you can still do the while (r - l <= 3), just paste the $$$\log_2(N)$$$ variant inside the loop.