### random_boi's blog

By random_boi, history, 19 months ago, ,

So I know how to do ternary search on a function which is first strictly increasing and then strictly decreasing, but if the function is not strictly increasing but rather non decreasing and then non increasing, is it possible to modify our ternary search to obtain the maximum for such function?

• +12

 » 19 months ago, # | ← Rev. 2 →   +38 Think of testcase like this: 1, 1, 1, 1, 1, .... 1, 1, 2, 1, 1, ... 1, 1, 1. We need to find 2, but it is obviously impossible, as we won`t have any additional iformation if we are given the answer that current element value is 2.
 » 19 months ago, # |   -21 The problem with the ternary search are the equal numbers. So usually you do it with doubles to avoid collisions.
•  » » 19 months ago, # ^ | ← Rev. 2 →   0 The actual reason why you see ternary search used in problems that involve functions on reals is that for reasonable functions it's numerically stable. (Small rounding errors when evaluating the function will not produce a large error in the computed result. If you get an incorrect result of comparison due to rounding but your two probes are still far away from each other, it does not matter which third you discard as the maximum is in the middle third anyway.)People often use it in discrete settings as well (e.g., find the maximum of an array that increases and then decreases), but in those settings there are better solutions. E.g., you can use binary search on the differences of the array, which is an equal amount of code and finds the maximum in fewer iterations.
•  » » » 8 months ago, # ^ |   0 I didn't get your idea. If have equal elements, the difference array (derivative) can be 0 at any point. If you hit zero element which side are you going to pick?
 » 8 months ago, # |   +6 I guess this blog is what you are looking for.