Skip to content

Commit 689a09a

Browse files
djeadabregman-arie
andauthored
Convert binary search to iterative, add helper functions and main with complexity docstring while preserving functionality (#10552)
Co-authored-by: Arie Bregman <[email protected]>
1 parent 70f382d commit 689a09a

File tree

1 file changed

+27
-13
lines changed

1 file changed

+27
-13
lines changed

Diff for: coding/python/binary_search.py

+27-13
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,42 @@
11
#!/usr/bin/env python
22

33
import random
4-
from typing import List
4+
from typing import List, Optional
55

66

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]:
88
"""
99
A Binary Search Example which has O(log n) time complexity.
1010
"""
11-
if lb <= ub:
12-
mid: int = lb + (ub - lb) // 2
11+
while lb <= ub:
12+
mid = lb + (ub - lb) // 2
1313
if arr[mid] == target:
1414
return mid
1515
elif arr[mid] < target:
16-
return binary_search(arr, mid + 1, ub, target)
16+
lb = mid + 1
1717
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}")
2139

2240

2341
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

Comments
 (0)