chore(Python): added ternary_search (#274)

pull/281/head
Ishita Tiwari 2021-04-29 21:22:03 +05:30 committed by GitHub
parent 312abef10b
commit 4d484eca5d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 48 additions and 0 deletions

View File

@ -17,6 +17,7 @@
1. [Binary Search](searching/binary_search.py)
2. [Jump Search](searching/jump_search.py)
3. [Linear Search](searching/linear_search.py)
4. [Ternary Search](searching/ternary_search.py)
## Sorting
1. [Bubble Sort](sorting/bubble_sort.py)

View File

@ -0,0 +1,47 @@
"""
TERNARY SEARCH
Time Complexity: O(log3 N)
Working: Similar to binary search but here we have two searc point (mid)
Steps:
1. Compare with elements at mid1 and mid2. Stop if found
2. If more than mid1 and less than mid2 - working field is the second part
3. If less than mid1 - working field is the first part
4. If more than mid2 - working field is the third part
"""
arr = [10, 13, 46, 51, 139, 467]
targets = [2, 467]
def ternarySearch(arr, target):
left, right = 0, len(arr) - 1
index = -1
while(left <= right):
mid1, mid2 = left + (right - left) // 3, right - (right - left) // 3
# checking for condition 1
if target == arr[mid1]:
index = mid1
break
if target == arr[mid2]:
index = mid2
break
# checking for condition 2
if target > arr[mid1] and target < arr[mid2]:
left, right = mid1 + 1, mid2 - 1
# checking for condition 3
elif target < arr[mid1]:
right = mid1 - 1
# checking for condition 4
else:
left = mid2 + 1
return index
for target in targets:
result = ternarySearch(arr, target)
if result == -1:
print(target, "is not present in", arr)
else:
print(target, "is present in the position:", result + 1)