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