In this article, we will implement a ternary search algorithm and compare its performance with binary search algorithm.

Prerequisite:

Binary Search Algorithm – Iterative and Recursive Implementation

 
In Ternary Search, we divide our array into three parts (by taking two mid) and discard two-third of our search space at each iteration. At first look, it seems that ternary search might be faster than binary search as its time complexity on an input containing n items should be O(log3n), which is less than the time complexity of binary search O(log2n). Before analyzing this claim, let’s take a look at its C, Java, and Python implementation first.

C


Download  Run Code

Output:

Element found at index 2

Java


Download  Run Code

Output:

Element found at index 2

Python


Download  Run Code

Output:

Element found at index 2

As we can see, at each iteration, ternary search makes at most 4 comparisons as compared to binary search, which only makes 2 comparisons. So,

Ternary Search complexity analysis

 
For Binary search – T(n) = 2clog2n + O(1)
For Ternary search – T(n) = 4clog3n + O(1)

 
By applying simple mathematics, we can establish that the time taken by ternary search is equal to 2.log32 times the time taken binary search algorithm.

Now since 2.log32 > 1, we actually get more comparisons with the ternary search.

Therefore, a ternary search will still give the same asymptotic complexity O(log(n)) search time but adds complexity to the implementation. The same argument is valid for a quaternary search or k–nary search for any other higher order.

As pointed out by Oriba Desu in the comments below, we can use a ternary search to find the extremum (minimum or maximum) of an unimodal function.