Last active
November 15, 2018 17:38
-
-
Save RafaelBroseghini/db23ad4de08429860d9fa0c1fdf2e302 to your computer and use it in GitHub Desktop.
Iterative and Recursive Binary Search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Both binary search functions implemented below assume the element being searched | |
is an integer but this can certainly be done with strings as well. | |
""" | |
# Iterative Binary Search | |
def iterative_binary_search(arr: list, element: int) -> bool: | |
start = 0 | |
end = len(arr) - 1 | |
while start <= end: | |
mid = (end+start) // 2 | |
print(start, mid, end) | |
if element == arr[mid]: | |
return True | |
elif element < arr[mid]: | |
end = mid - 1 | |
else: | |
start = mid + 1 | |
return False | |
# Recursive Binary Search | |
def recursive_binary_search(arr: list, start: int, end: int, elem: int) -> bool: | |
if start > end: | |
return False | |
mid = (end + start) // 2 | |
if elem == arr[mid]: | |
return True | |
elif elem < arr[mid]: | |
end = mid - 1 | |
return recursive_binary_search(arr, start, end, elem) | |
else: | |
start = mid + 1 | |
return recursive_binary_search(arr, start, end, elem) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment