Skip to content

Commit 77cfed5

Browse files
add ternary search
1 parent 4968dd6 commit 77cfed5

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""
2+
Ternary search is a divide and conquer algorithm that can be used to find an element in an array.
3+
It is similar to binary search where we divide the array into two parts but in this algorithm,
4+
we divide the given array into three parts and determine which has the key (searched element).
5+
We can divide the array into three parts by taking mid1 and mid2.
6+
Initially, l and r will be equal to 0 and n-1 respectively, where n is the length of the array.
7+
mid1 = l + (r-l)/3
8+
mid2 = r – (r-l)/3
9+
10+
Note: Array needs to be sorted to perform ternary search on it.
11+
T(N) = O(log3(N))
12+
log3 = log base 3
13+
"""
14+
def ternary_search(l, r, key, arr):
15+
while r >= l:
16+
17+
mid1 = l + (r-l) // 3
18+
mid2 = r - (r-l) // 3
19+
20+
if key == arr[mid1]:
21+
return mid1
22+
if key == mid2:
23+
return mid2
24+
25+
if key < arr[mid1]:
26+
# key lies between l and mid1
27+
r = mid1 - 1
28+
elif key > arr[mid2]:
29+
# key lies between mid2 and r
30+
l = mid2 + 1
31+
else:
32+
# key lies between mid1 and mid2
33+
l = mid1 + 1
34+
r = mid2 - 1
35+
36+
# key not found
37+
return -1

0 commit comments

Comments
 (0)