devops-exercises/coding/python/binary_search.py

28 lines
733 B
Python
Raw Normal View History

2019-12-02 20:54:31 +02:00
#!/usr/bin/env python
import random
2020-01-17 18:15:07 +05:30
def binary_search(arr, lb, ub, target):
2021-06-27 23:01:11 +05:30
"""
A Binary Search Example which has O(log n) time complexity.
2021-06-27 23:01:11 +05:30
"""
2020-01-17 18:15:07 +05:30
if lb <= ub:
mid = ub + lb // 2
if arr[mid] == target:
2019-12-02 20:54:31 +02:00
return mid
2020-01-17 18:15:07 +05:30
elif arr[mid] < target:
return binary_search(arr, mid + 1, ub, target)
2019-12-02 20:54:31 +02:00
else:
2020-01-17 18:15:07 +05:30
return binary_search(arr, lb, mid - 1, target)
2019-12-02 20:54:31 +02:00
else:
return -1
2021-06-27 23:01:11 +05:30
if __name__ == '__main__':
rand_num_li = sorted([random.randint(1, 50) for _ in range(10)])
target = random.randint(1, 50)
print("List: {}\nTarget: {}\nIndex: {}".format(
rand_num_li, target,
binary_search(rand_num_li, 0, len(rand_num_li) - 1, target)))