Skip to content

Instantly share code, notes, and snippets.

@ioanzicu
Created July 28, 2022 05:10
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 ioanzicu/da548ab540147897d3b4715fb7b62ea1 to your computer and use it in GitHub Desktop.
Save ioanzicu/da548ab540147897d3b4715fb7b62ea1 to your computer and use it in GitHub Desktop.
Binary Search iterative and recursive versions implementation in Python 3.
def binary_search_iterative(nums, target):
low = 0
high = len(nums) - 1
while low <= high:
middle = (low + high) // 2
curr_item = nums[middle]
if curr_item == target:
return True
elif curr_item > target:
high = middle - 1
else:
low = middle + 1
return False
def binary_search_reccursive(nums, target, low, high):
if low > high:
return False
middle = (low + high) // 2
curr_item = nums[middle]
if curr_item == target:
return True
elif curr_item > target:
return binary_search_reccursive(nums, target, low, middle - 1)
else:
return binary_search_reccursive(nums, target, middle + 1, high)
nums = [0, 1, 5, 9, 22, 33, 44, 88, 333, 555, 666, 999]
result = binary_search_iterative(nums, 100)
print(result)
result = binary_search_reccursive(nums, 100, 0, len(nums)-1)
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment