2019-12-02 20:54:31 +02:00
|
|
|
#!/usr/bin/env python
|
|
|
|
|
|
|
|
import random
|
2025-03-26 21:22:05 -01:00
|
|
|
from typing import List, Optional
|
2019-12-02 20:54:31 +02:00
|
|
|
|
2021-07-12 02:02:57 +03:00
|
|
|
|
2025-03-26 21:22:05 -01:00
|
|
|
def binary_search(arr: List[int], lb: int, ub: int, target: int) -> Optional[int]:
|
2021-06-27 23:01:11 +05:30
|
|
|
"""
|
2021-07-12 02:02:57 +03:00
|
|
|
A Binary Search Example which has O(log n) time complexity.
|
2021-06-27 23:01:11 +05:30
|
|
|
"""
|
2025-03-26 21:22:05 -01:00
|
|
|
while lb <= ub:
|
|
|
|
mid = lb + (ub - lb) // 2
|
2020-01-17 18:15:07 +05:30
|
|
|
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:
|
2025-03-26 21:22:05 -01:00
|
|
|
lb = mid + 1
|
2019-12-02 20:54:31 +02:00
|
|
|
else:
|
2025-03-26 21:22:05 -01:00
|
|
|
ub = mid - 1
|
|
|
|
return -1
|
|
|
|
|
|
|
|
|
|
|
|
def generate_random_list(size: int = 10, lower: int = 1, upper: int = 50) -> List[int]:
|
|
|
|
return sorted(random.randint(lower, upper) for _ in range(size))
|
|
|
|
|
|
|
|
|
|
|
|
def find_target_in_list(target: int, lst: List[int]) -> int:
|
|
|
|
return binary_search(lst, 0, len(lst) - 1, target)
|
|
|
|
|
|
|
|
|
|
|
|
def main():
|
|
|
|
"""
|
|
|
|
Executes the binary search algorithm with a randomly generated list.
|
|
|
|
Time Complexity: O(log n)
|
|
|
|
"""
|
|
|
|
rand_num_li = generate_random_list()
|
|
|
|
target = random.randint(1, 50)
|
|
|
|
index = find_target_in_list(target, rand_num_li)
|
|
|
|
print(f"List: {rand_num_li}\nTarget: {target}\nIndex: {index}")
|
2019-12-02 20:54:31 +02:00
|
|
|
|
2021-07-12 02:02:57 +03:00
|
|
|
|
2021-06-27 23:01:11 +05:30
|
|
|
if __name__ == '__main__':
|
2025-03-26 21:22:05 -01:00
|
|
|
main()
|