0

So I'm writing a recursive binary search algorithim in Python and it's been working great ...... except when I tried a certain number.

I'm working off of a list of 10,000 randomized numbers that have been sorted.

It eventually fails with this error:

RecursionError: maximum recursion depth exceeded while calling a Python object

I've put in counters inside the function to keep track of the low/high points and current search count. When I run bSearch(3333), I get the above error and this weird output...

0 None 1
0 4998 2
0 2498 3
0 1248 4
0 623 5
312 623 6
312 466 7
312 388 8
312 349 9
331 349 10
331 339 11
336 339 12
338 339 13
338 337 14
338 337 15

It just keeps repeating 338 337 until it reaches the cursions ceiling.

Here's my function:

def bSearch(list, value, lowPoint=0, highPoint=None, searchNum=1):
    print(lowPoint,highPoint,searchNum)
    searchNum += 1
    if highPoint is None:
        highPoint = len(list) - 1
    if lowPoint == highPoint:
        if list[lowPoint] == value:
            return lowPoint, searchNum
        else:
            return -1, searchNum
    midPoint = (lowPoint + highPoint) // 2
    if list[midPoint] > value:
        return bSearch(list, value, lowPoint, midPoint - 1, searchNum)
    elif list[midPoint] < value:
        return bSearch(list, value, midPoint + 1, highPoint, searchNum)
    else:
        return midPoint

1 Answer 1

1

The reason is you haven't handled one terminating condition. when your lower limit is higher than your higher limit, This means the element you are searching is not there in the list you should return a -1 there.

def bSearch(list, value, lowPoint=0, highPoint=None, searchNum=1):
    print(lowPoint,highPoint,searchNum)
    searchNum += 1
    if highPoint is None:
        highPoint = len(list) - 1
    if lowPoint == highPoint:
        if list[lowPoint] == value:
            return lowPoint, searchNum
        else:
            return -1, searchNum
    if lowPoint > highPoint:
        return -1,searchNum
    midPoint = (lowPoint + highPoint) // 2
    if list[midPoint] > value:
        return bSearch(list, value, lowPoint, midPoint - 1, searchNum)
    elif list[midPoint] < value:
        return bSearch(list, value, midPoint + 1, highPoint, searchNum)
    else:
        return midPoint
Sign up to request clarification or add additional context in comments.

3 Comments

-__- Should have thought the terminating conditions through more! Thanks!
I also just combined the two like this: if lowPoint >= highPoint:
Yeah that makes sense \m/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.