# Time complexity O(log(n)) and space complexity is O(1)
### Using three pointers - left, right and middle
### We keep adjusting the three pointers and quit when
### left pointer crosses the right pointer
def binarySearch(array, target):
= 0
left = len(array) - 1
right
while left <= right:
= (left+right) // 2
middle = array[middle]
potentialMatch
if target == potentialMatch:
return middle
elif target < potentialMatch:
= middle - 1
right
else:
= middle + 1
left
return -1
Binary Search
Binary search using Iterative Method
= [0,1,21,33,45,61,71,72,73]
array = 33 target
=array,target=target) binarySearch(array
3
Binary search using Recursion
# O(log(n)) time complexity ! O(log(n)) space complexity
def binarySearch(array,target):
return binarySearchHelper(array,target,0,len(array)-1)
def binarySearchHelper(array,target,left,right):
if left > right:
return -1
= (left+right) // 2
middle = array[middle]
potentialMatch if target == potentialMatch:
return middle
elif target < potentialMatch:
return binarySearchHelper(array,target,left,middle-1)
else:
return binarySearchHelper(array,target,middle+1,right)
binarySearch(array,target)
3