Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert binary search to iterative for improved efficiency #10552

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 27 additions & 13 deletions coding/python/binary_search.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,42 @@
#!/usr/bin/env python

import random
from typing import List
from typing import List, Optional


def binary_search(arr: List[int], lb: int, ub: int, target: int) -> int:
def binary_search(arr: List[int], lb: int, ub: int, target: int) -> Optional[int]:
"""
A Binary Search Example which has O(log n) time complexity.
"""
if lb <= ub:
mid: int = lb + (ub - lb) // 2
while lb <= ub:
mid = lb + (ub - lb) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
return binary_search(arr, mid + 1, ub, target)
lb = mid + 1
else:
return binary_search(arr, lb, mid - 1, target)
else:
return -1
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}")


if __name__ == '__main__':
rand_num_li: List[int] = sorted([random.randint(1, 50) for _ in range(10)])
target: int = 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)))
main()
Loading