'Binary Search - Is this correct? and how to get position of search term
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
Solution 1:[1]
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)
Solution 2:[2]
Answer to part 2: you need to return binsearch(i, arr) in the elif and else statements.
Edit:
Answering part 3 as well, you can add the current index as a third variable of binsearch and update it each recursion:
def binsearch(i, arr, index=0):
mid = len(arr)//2
index += mid
# If the item is found return True and the index
if i == arr[mid]:
return True, index
# i not in list
elif not mid:
return False
# else recursively search if i is at the mid point
elif i < arr[mid]:
arr = arr[:mid]
index -= mid
else:
arr = arr[mid:]
return binsearch(i,arr, index)
arr =[1,2,3,4,5,10,12,13,14,15,17,19]
for i in range(20):
print(i, binsearch(i, arr))
Output:
0 False
1 (True, 0)
2 (True, 1)
3 (True, 2)
4 (True, 3)
5 (True, 4)
6 False
7 False
8 False
9 False
10 (True, 5)
11 False
12 (True, 6)
13 (True, 7)
14 (True, 8)
15 (True, 9)
16 False
17 (True, 10)
18 False
19 (True, 11)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Diego Fidalgo |
| Solution 2 |
