|
1 | 1 | #!/usr/bin/env python
|
2 | 2 |
|
3 | 3 | import random
|
4 |
| -from typing import List |
| 4 | +from typing import List, Optional |
5 | 5 |
|
6 | 6 |
|
7 |
| -def binary_search(arr: List[int], lb: int, ub: int, target: int) -> int: |
| 7 | +def binary_search(arr: List[int], lb: int, ub: int, target: int) -> Optional[int]: |
8 | 8 | """
|
9 | 9 | A Binary Search Example which has O(log n) time complexity.
|
10 | 10 | """
|
11 |
| - if lb <= ub: |
12 |
| - mid: int = lb + (ub - lb) // 2 |
| 11 | + while lb <= ub: |
| 12 | + mid = lb + (ub - lb) // 2 |
13 | 13 | if arr[mid] == target:
|
14 | 14 | return mid
|
15 | 15 | elif arr[mid] < target:
|
16 |
| - return binary_search(arr, mid + 1, ub, target) |
| 16 | + lb = mid + 1 |
17 | 17 | else:
|
18 |
| - return binary_search(arr, lb, mid - 1, target) |
19 |
| - else: |
20 |
| - return 0 |
| 18 | + ub = mid - 1 |
| 19 | + return -1 |
| 20 | + |
| 21 | + |
| 22 | +def generate_random_list(size: int = 10, lower: int = 1, upper: int = 50) -> List[int]: |
| 23 | + return sorted(random.randint(lower, upper) for _ in range(size)) |
| 24 | + |
| 25 | + |
| 26 | +def find_target_in_list(target: int, lst: List[int]) -> int: |
| 27 | + return binary_search(lst, 0, len(lst) - 1, target) |
| 28 | + |
| 29 | + |
| 30 | +def main(): |
| 31 | + """ |
| 32 | + Executes the binary search algorithm with a randomly generated list. |
| 33 | + Time Complexity: O(log n) |
| 34 | + """ |
| 35 | + rand_num_li = generate_random_list() |
| 36 | + target = random.randint(1, 50) |
| 37 | + index = find_target_in_list(target, rand_num_li) |
| 38 | + print(f"List: {rand_num_li}\nTarget: {target}\nIndex: {index}") |
21 | 39 |
|
22 | 40 |
|
23 | 41 | if __name__ == '__main__':
|
24 |
| - rand_num_li: List[int] = sorted([random.randint(1, 50) for _ in range(10)]) |
25 |
| - target: int = random.randint(1, 50) |
26 |
| - print("List: {}\nTarget: {}\nIndex: {}".format( |
27 |
| - rand_num_li, target, |
28 |
| - binary_search(rand_num_li, 0, len(rand_num_li) - 1, target))) |
| 42 | + main() |
0 commit comments