Ternary search

Last updated • 1 min readFrom Wikipedia, The Free Encyclopedia

A ternary search algorithm [1] is a technique in computer science for finding the minimum or maximum of a unimodal function.

Contents

The function

Assume we are looking for a maximum of and that we know the maximum lies somewhere between and . For the algorithm to be applicable, there must be some value such that

Algorithm

Let be a unimodal function on some interval . Take any two points and in this segment: . Then there are three possibilities:

choice points and :

Run time order
(by the Master Theorem)

Recursive algorithm

defternary_search(f,left,right,absolute_precision)->float:"""Left and right are the current bounds;    the maximum is between them.    """ifabs(right-left)<absolute_precision:return(left+right)/2left_third=(2*left+right)/3right_third=(left+2*right)/3iff(left_third)<f(right_third):returnternary_search(f,left_third,right,absolute_precision)else:returnternary_search(f,left,right_third,absolute_precision)

Iterative algorithm

defternary_search(f,left,right,absolute_precision)->float:"""Find maximum of unimodal function f() within [left, right].    To find the minimum, reverse the if/else statement or reverse the comparison.    """whileabs(right-left)>=absolute_precision:left_third=left+(right-left)/3right_third=right-(right-left)/3iff(left_third)<f(right_third):left=left_thirdelse:right=right_third# Left and right are the current bounds; the maximum is between themreturn(left+right)/2

See also

References

  1. "Ternary Search". cp-algorithms.com. Retrieved 21 August 2023.