Currently, when I search for the element that is at the midpoint it returns the correct index, but for any other element it does not work for me.
I think I am making a mistake when I split the array:
aList = [1,3,5,6,8,9,10,12,34,56,78,456]
def recursiveBinarySearch(aList, target):
#aList = sorted(aList)
if len(aList) == 0:
return False
else:
midpoint = len(aList) // 2
if aList[midpoint] == target:
return aList.index(target)
else:
if target < aList[midpoint]:
return recursiveBinarySearch(aList[:midpoint],target)
else:
return recursiveBinarySearch(aList[midpoint+1:],target)
print(recursiveBinarySearch(aList,9))
That is because every time you make a recursive call, a different modified list is passed and the index will change in every call. For example, if you search for a number in second half of the array, the final returned value will be less than len(aList)/2
because only this part of the array will be passed in the next iteration.
The workaround is to pass start
and end
points of the list instead of splitting the list.
aList = [1,3,5,6,8,9,10,12,34,56,78,456]
def recursiveBinarySearch(aList, target, start, end):
#aList = sorted(aList)
if end-start+1 <= 0:
return False
else:
midpoint = start + (end - start) // 2
if aList[midpoint] == target:
return midpoint
else:
if target < aList[midpoint]:
return recursiveBinarySearch(aList, target, start, midpoint-1)
else:
return recursiveBinarySearch(aList ,target, midpoint+1, end)
print(recursiveBinarySearch(aList,455, 0, len(aList)))
Tried editing the accepted answer because it fails when searching for numbers that are higher than those in the list but for some reason the OP did not accept the edits, meaning that answer is still wrong. That being the case, I will post the answer here. Not only does this answer fix the IndexError
when asked to find a value greater than one that is not in the list, it also changes the args to be kwargs so we don't have to pass them in every time we call the function
aList = [-1,1,3,5,6,8,9,10,12,34,56,78,456]
def binary_search(arr,item,low = 0, high = None):
if high == None:
high = len(arr)
mid = low + (high-low) //2
if high - low + 1 <= 0 or mid==high:
return False
else:
guess = arr[mid]
if guess == item:
return mid
if item < guess:
return binary_search(arr, item, low, mid)
else:
return binary_search(arr, item, (mid+1), high)
(binary_search(aList,457))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With