-4

I am trying to apply the Binary Search algorithm (the recursive way) and I'm having this error

def BinarySearchRec(tab, x):
    mid = len(tab) // 2
    if len(tab) == 0:
        return False
    if tab[mid] > x:
        return BinarySearchRec(tab[:mid], x)
    elif tab[mid] < x:
        return BinarySearchRec(tab[mid:], x)
    else:
        return mid

I tried to 1 and retrive one when i call the function back but didn't work on all cases

4
  • 1
    Please update your question with an example of how you call your function when it exceeds maximum recursion depth. Commented Nov 19, 2022 at 14:44
  • Add a print statement or use a debugger to monitor the value of mid from call to call. You'll see that tab[:mid] and tab[mid:] eventually are the same as tab, so your recursion isn't progressing. Commented Nov 19, 2022 at 14:44
  • 2
    When the length of the list is 1 and you try to slice tab[mid:], you will get the same list, which causes the recursion to fail. Commented Nov 19, 2022 at 14:48
  • 1
    Welcome to Stack Overflow. "I tried to 1 and retrive one when i call the function back but didn't work on all cases" This isn't understandable. Please read How to Ask and minimal reproducible example, and clearly show: how do you call the function in order to cause a problem? What should happen for that input? What does happen instead, and how is that different? Commented Nov 19, 2022 at 15:23

1 Answer 1

1

When mid=0 and tab[mid] < x, the code gets stuck because BinarySearchRec(tab[mid:], x) will loop forever with the same inputs: (tab[mid:],x) -> (tab[0:],x) -> (tab,x) .

As a proof, you can try the following example:

tab = [1]
x   = 2
BinarySearchRec(tab, x)
# recursion error raised

The easiest solution is to make sure that the array tab decreases in size every time you perform recursion:

def BinarySearchRec(tab, x, i=0, j=None):
    # edit: added (i,j) bounds, instead of array slices tab[a:b]
    #       this is much faster, and lowers the time complexity
    #       per recursion to O(1) instead of O(n)
    if j is None: j = len(tab)-1
    mid = (i+j)//2
    if j < i:
        return False
    elif tab[mid] == x:
        return mid
    elif x < tab[mid]:
        return BinarySearchRec(tab, x, i, mid-1)
    elif tab[mid] < x:
        return BinarySearchRec(tab, x, mid+1, j)

tab = [1]
x   = 2
BinarySearchRec(tab, x)
# now it works

In the new code, the tab array is trimmed using either mid+1 or mid-1, since we can discard mid as a solution when tab[mid] != x. This makes sure that tab always decreases at least one element in size, and hence the code does not crash. Cheers,


Function testing:

assert BinarySearchRec([1,2,3],-1) == False # ok
assert BinarySearchRec([1,2,3], 1) == 0     # ok
assert BinarySearchRec([1,2,3], 2) == 1     # ok
assert BinarySearchRec([1,2,3], 3) == 2     # ok
assert BinarySearchRec([1,2,3], 4) == False # ok
Sign up to request clarification or add additional context in comments.

2 Comments

I edited and tested the code (I even added (i,j) bounds to improve its time complexity). Does it work now?
The new code passed all the test cases in your example :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.