Skip to content

Instantly share code, notes, and snippets.

@RafaelBroseghini
Last active November 15, 2018 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RafaelBroseghini/db23ad4de08429860d9fa0c1fdf2e302 to your computer and use it in GitHub Desktop.
Save RafaelBroseghini/db23ad4de08429860d9fa0c1fdf2e302 to your computer and use it in GitHub Desktop.
Iterative and Recursive Binary Search
"""
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