I am implementing a Binary Search algorithm that returns:
- In the case the
keyis in the list:Trueand the position of thekeyI am looking for; - In the case the
keyis not in the list: it returnsFalse
Here is my code of the function: Bin_Search (A, l, r, key)
def Bin_Search (A, l, r, key):
if l == r:
if A[l] == key:
return True, l
else:
return False
mid = (l+r)//2
if A[mid] == key:
return True, mid
if A[mid] < key:
return Bin_Search(A, l, mid-1, key)
else:
return Bin_Search(A, mid+1, r, key)
But I am having trouble since sometimes it works and sometimes not.
For example, implementing the function on the array A to find key = 14
A = [35, 21, 49, 0, 46, 5, 1, 14, 50, 34]
Bin_Search (A, 0, len(A), 14)
I get the following error:
RecursionError Traceback (most recent call last)
<ipython-input-174-380483777517> in <module>
19
20 A = [35, 21, 49, 0, 46, 5, 1, 14, 50, 34]
---> 21 Bin_Search(A, 0, len(A), 14)
<ipython-input-174-380483777517> in Bin_Search(A, l, r, key)
13
14 if A[mid] < key:
---> 15 return Bin_Search(A, l, mid-1, key)
16 else:
17 return Bin_Search(A, mid+1, r, key)
<ipython-input-174-380483777517> in Bin_Search(A, l, r, key)
15 return Bin_Search(A, l, mid-1, key)
16 else:
---> 17 return Bin_Search(A, mid+1, r, key)
18
19
<ipython-input-174-380483777517> in Bin_Search(A, l, r, key)
13
14 if A[mid] < key:
---> 15 return Bin_Search(A, l, mid-1, key)
16 else:
17 return Bin_Search(A, mid+1, r, key)
<ipython-input-174-380483777517> in Bin_Search(A, l, r, key)
15 return Bin_Search(A, l, mid-1, key)
16 else:
---> 17 return Bin_Search(A, mid+1, r, key)
18
19
... last 1 frames repeated, from the frame below ...
<ipython-input-174-380483777517> in Bin_Search(A, l, r, key)
15 return Bin_Search(A, l, mid-1, key)
16 else:
---> 17 return Bin_Search(A, mid+1, r, key)
18
19
RecursionError: maximum recursion depth exceeded in comparison
Why do I get this error? Which part of the code I must fix in order that it works properly?
return boolis never used? recursive not terminate.Bin_AearchandBinary_Search?