Created
July 28, 2022 05:10
-
-
Save ioanzicu/da548ab540147897d3b4715fb7b62ea1 to your computer and use it in GitHub Desktop.
Binary Search iterative and recursive versions implementation in Python 3.
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
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