Understanding the use of return
statement in recursion
For example in Binary Search:
def binary_search_recur(array,start,end,item):
middle = int((start+end)/2)
#print (middle)
if (start>end):
return -1
else:
if array[middle]==item:
return middle
elif array[middle]>item:
return binary_search_recur(array,start,middle-1,item)
else:
return binary_search_recur(array,middle+1,end,item)
Calling the function with
array = [27,45,76,81,92,101,291]
binary_search_recur(array,0,len(array)-1,27)
Works fine if I add return
statement everywhere, but it does not return 0
(the index of the searched element in the example) if I remove the return
statement like below
else:
if array[middle]==item:
return middle
elif array[middle]>item:
binary_search_recur(array,start,middle-1,item) #retrun statement removed
else:
binary_search_recur(array,middle+1,end,item) #retrun statement removed
My point is, i would want to return when I find the element so I return the index middle
, or if the element is not present at all so in that case I return -1
, otherwise I am just calling the function recursively with updated start
and end
index, Just like merge sort
merge_sort(l)
merge_sort(r)
merge(l,r,array)
So I dont understand why removing the return
statement like in the example does not return the op. Any suggestions would be great.