Binary Search
Listing two variants: One recursive and one iterative
# In this recursive version we are just not returning True/False. We are returning the index position
# of the array where the match happened. We are using a global variable to note this index
idx = -1
def binSearch(V, arr, first, last):
global idx
mid = (first + last) / 2
#print arr, first, last, mid
if V == arr[mid]:
#print 'found: ', mid
idx = mid
return mid
if V < arr[mid]:
binSearch(V, arr, 0, mid)
if V > arr[mid]:
binSearch(V, arr, mid+1, len(arr) - 1)Last updated
Was this helpful?