Ternary Search Article Index for
Ternary
Articles about
Ternary Search
Website Links For
Search
 

Information About

Ternary Search





THE FUNCTION


Assume we are looking for a maximum of f(x) and that we know the maximum lies somewhere between A and B. For the algorithm to be applicable, there must be some value ''x'' such that
  • for all ''a'',''b'' with A ≤ ''a'' < ''b'' ≤ ''x'', we have f(''a'') < f(''b''), and

  • for all ''a'',''b'' with ''x'' ≤ ''a'' < ''b'' ≤ B, we have f(''a'') > f(''b'').



THE ALGORITHM


function ternarySearch(f, left, right, absolutePrecision) //left and right are the current bounds; the maximum is between them
if (right-left < absolutePrecision) return (left+right)/2
  • 2+right)/3

  • 2)/3

  • if (f(leftThird) < f(rightThird))

return ternarySearch(f, leftThird, right, absolutePrecision)
else
return ternarySearch(f, left, rightThird, absolutePrecision)