I am a beginner to programming. I have three questions about my binary search code I wrote (in Python): (1) When I compared my code to the ones I found on the net, I see that everyone uses low and high values parameters. Wondering if mine can have errors that I am not seeing or is it just that the high/low parameters make the code more readable? I thought mine follows the recursive way of thinking (at least for me).
(2) edit: This part has since been answered.—>> I can’t get it to return True or False for the answer. Is it because the True/False is getting returned to the recursive function and not the print? How can I get it to return True, or False answer?
(3) I can’t figure out how to get the position of the search term in the list (of course, not using index function). I thought I could somehow use the “mid” variable which was in the code, but couldn’t. Can you give me some ideas how to get its position in the list?.
def binsearch(i, arr): mid = ((len(arr)-1)//2) # If we can't divide the list any further and it is not i , return false if mid == 0: if i != arr[mid]: # print ("False") return False # else recursively search if i is at the mid point if i == arr[mid]: # print ("True") return True elif i < arr[mid]: arr = arr[0:mid+1] binsearch(i,arr) else: arr = arr[mid+1:] binsearch(i,arr) i = 19 #1=1 #i=16 #i=17 arr =[1,2,3,4,5,10,12,13,14,15,17,19] print(binsearch(i, arr))
Thanks
Arun
Advertisement
Answer
The problem here is that you’re not returning the value on the recursive cases. Refactor your code to this and it should work.
if i == arr[mid]: return True elif i < arr[mid]: arr = arr[0:mid+1] else: arr = arr[mid+1:] return binsearch(i, arr)