Skip to content

Commit fa11a7b

Browse files
authored
Merge pull request shivangdubey#272 from Aanchi-glitch2744/patch-1
Ternary Search algorithm in python
2 parents 890bc43 + 166c5e7 commit fa11a7b

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

Diff for: python/Ternary_Search.py

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
"""
2+
This is a type of divide and conquer algorithm which divides the search space into
3+
3 parts and finds the target value based on the property of the array or list
4+
(usually monotonic property).
5+
6+
Time Complexity : O(log3 N)
7+
Space Complexity : O(1)
8+
"""
9+
10+
def ternary_search(ar, l, r, key):
11+
12+
if (r >= l):
13+
# Find the mid1 and mid2
14+
mid1 = l + (r - l) //3
15+
mid2 = r - (r - l) //3
16+
17+
if (ar[mid1] == key):
18+
return mid1
19+
if (ar[mid2] == key):
20+
return mid2
21+
22+
if (key < ar[mid1]):
23+
# The key lies in between l and mid1
24+
r = mid1 - 1
25+
return ternary_search(ar, l, r, key)
26+
27+
elif (key > ar[mid2]):
28+
# The key lies in between mid2 and r
29+
l = mid2 + 1
30+
return ternary_search(ar, l, r, key)
31+
32+
else:
33+
# The key lies in between mid1 and mid2
34+
l = mid1 + 1
35+
r = mid2 - 1
36+
return ternary_search(ar, l, r, key)
37+
38+
return -1
39+
40+
# Driver Code
41+
arr = [int(item) for item in input("Enter the array elements : ").split()]
42+
key = int(input("Enter the number to be searched : "))
43+
arr.sort()
44+
l = 0
45+
r = len(arr) - 1
46+
print("Index of number is :",ternary_search(arr, l, r, key))
47+
48+
"""
49+
Sample I/O :
50+
51+
Input :
52+
Enter the array elements : 1 2 3 4 5
53+
Enter the number to be searched : 3
54+
55+
Output :
56+
Index of key is : 2
57+
"""

0 commit comments

Comments
 (0)