-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathternary_search_iter.py
67 lines (50 loc) · 1.21 KB
/
ternary_search_iter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# Python program to illustrate iterative
# approach to ternary search
# Function to perform Ternary Search
def ternarySearch(l, r, key, ar):
while r >= l:
# Find mid1 and mid2
mid1 = l + (r-l) // 3
mid2 = r - (r-l) // 3
# Check if key is at any mid
if key == ar[mid1]:
return mid1
if key == ar[mid2]:
return mid2
# Since key is not present at mid,
# Check in which region it is present
# Then repeat the search operation in that region
if key < ar[mid1]:
# key lies between l and mid1
r = mid1 - 1
elif key > ar[mid2]:
# key lies between mid2 and r
l = mid2 + 1
else:
# key lies between mid1 and mid2
l = mid1 + 1
r = mid2 - 1
# key not found
return -1
# Driver code
# Get the list
# Sort the list if not sorted
ar = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Starting index
l = 0
# end element index
r = 9
# Checking for 5
# Key to be searched in the list
key = 5
# Search the key using ternary search
p = ternarySearch(l, r, key, ar)
# Print the result
print("Index of", key, "is", p)
# Checking for 50
# Key to be searched in the list
key = 50
# Search the key using ternary search
p = ternarySearch(l, r, key, ar)
# Print the result
print("Index of", key, "is", p)