Binary Search
Iterative Algorithm
def binary_search(nums: List[int], target: [int]) -> int | None:
left = 0
right = len(nums) - 1
# Less than or equal check is used in while condition to handle the case when there is one element
while left <= right:
# the middle (or average) of the range
mid = (right + left) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return NoneRecursive Algorithm
Resources
Last updated