I am having issues when returning the values from a recursive function. For example, in a very simple function called 'RBinSearch', I am trying to find the index of the key in an array. Unfortunately, I just cannot able to return the value (answer should be 4) based on my understanding.
For comparison, I have used a normal function with a loop to test the return (in a function called 'BinarySearch' here), which is working as expected. Can anyone please explain how the return behave inside a recursive function and where my understanding is incorrect? Thanks!
import math
import sys
def BinarySearch(array, key):
low=0
high=len(array)-1
while(low<=high):
mid=math.floor((low high)/2)
if(key==array[mid]):
return mid
elif(key<array[mid]):
high=mid-1
elif(key>array[mid]):
low=mid 1
return -1
def RBinSearch(array,low,high,key):
if(low<=high):
mid=math.floor((low high)/2)
print("Value of mid: ",mid)
if(key==array[mid]):
print("Found the value: ",mid)
return mid
sys.exit()
elif(key<array[mid]):
RBinSearch(array, low, mid-1, key)
else:
RBinSearch(array, mid 1, high, key)
return -1
arr=[4,8,10,15,18,21,24,27,29,33,34,37,39,41,43]
print("Index from while Bin search: ",BinarySearch(arr, 18))
print("The index found using the Binary search is: ",RBinSearch(arr, 0,len(arr)-1,18))
Output
CodePudding user response:
You need to return RBinSearch
result in your RBinSearch
function:
def RBinSearch(array, low, high, key):
if low <= high:
mid = math.floor((low high) / 2)
print("Value of mid: ", mid)
if key == array[mid]:
print("Found the value: ", mid)
return mid
elif key < array[mid]:
return RBinSearch(array, low, mid - 1, key)
else:
return RBinSearch(array, mid 1, high, key)
return -1
Also you shouldn't use sys.exit()
.