Ternary Search uses the principle of Divide And Conquer.
It is similar to Binary Search Algorithm. But here, we divide the sub-array into three parts rather than two parts. For this, we use two middle values mid1
and mid2
.
mid1
= low
+ ( ( high
- low
) / 3 )mid2
= high
– ( ( high
- low
) / 3 )
where, low
is the index of starting element of the sub-array to be searched, high
is the index of last element of that sub-array.
After finding the values of mid1
and mid2
, we compare key
with the values of input_array[mid1]
and input_array[mid2]
.
- If
key == input_array[mid1]
,key
is found at positionmid1
ofinput_array
. - If
key == input_array[mid2]
,key
is found at positionmid2
ofinput_array
. - If
key < input_array[mid1]
, we need to search thekey
in the first part of the sub-array. So,high = mid1 - 1
. Now the sub-array ends atmid1-1
. - If
key > input_array[mid2]
, we need to search thekey
in the third part of the sub-array. So,low = mid2 + 1
. Now the sub-array starts frommid2+1
. - If
input_array[mid1] < key < input_array[mid2]
, we need to search thekey
in the second part of the sub-array. So,low = mid1 + 1
andhigh = mid2 - 1
. Now the sub-array starts atmid1+1
and ends atmid2-1
.
Note : At each stage, the sub-array is reduced to one third of its length.
In this way, during each stage we check the possible range in which the key can lie in the sub-array and minimize the sub-array.
Let us look at ternary search with an example:
Let input_array
= {12,18,23,25,29,32,35,40,58,66} and key = 23
Advantage of Ternary Search:
During each comparison, 66%
of the elements are eliminated from the sub-array.
Disadvantage of binary search:
This algorithm does not work if the input_array
is not in sorted order.
Time Complexity : O(log3N)
Space Complexity : O(1)
Ternary Search is efficient than Binary Search and Linear Search in terms of its Time Complexity.
C++ CODE FOR TERNARY SEARCH:
TESTCASE :
Enter the length of array
5
Enter array elements in increasing order
14 35 67 89 90
Enter the element to be searched
67
key found at index 2