Ternary Search
November 10, 2017
We looked at binary search in the previous exercise. Today we look at ternary search. Instead of one mid
at the middle of the array, ternary search has two mid
s a third of the way from each end; two-thirds of the array is discarded at each recursive step.
Your task is to write a program that performs ternary search. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Here’s a solution in C99.
Build:
Output:
Like in the Python bisect module I have implemented a trisect_left, which finds an insert point for x. If x is already in the array the new x will be inserted at the left. Then tsearch_left will use trisect_left and find x, if it is there.
[…] looked at variants of binary search in two recent exercises. Today we look at a third […]