0
import math 

def BinarySearch( A , val , low , high ):
    if high < low :
        return -1 #not found 
    mid = low + (high - low ) /2 
    if A[mid] > val:
        return BinarySearch(A,val , low , high )
    if A[mid] < val :
        return BinarySearch(A,val,low,high)
    else: 
        return mid #found 


A = [ 12 , 23 , 2 , 33 , 123 , 4 , 5 , 2 , 54 , 555 , 21 ]
BinarySearch( A , 0 , 0, 10)

I tried to do Binary Search without using the bisect Module . But it gives an error such as this

 File "doubtrob.py", line 8, in BinarySearch
    return BinarySearch(A,val , low , high )
RuntimeError: maximum recursion depth exceeded

3 Answers 3

3
def BinarySearch( A , val , low , high ):
    if high < low :
        return -1 #not found                                                                                                                                 
    mid = low + (high - low ) /2
    if A[mid] > val:
        return BinarySearch(A, val , low , mid-1 )
    if A[mid] < val :
        return BinarySearch(A, val, mid+1 ,high)
    else:
        return mid #found 

recursion must have a end point. You are calling same parameters ever time so, it will never satisfy the high<low, so never terminates.

Sign up to request clarification or add additional context in comments.

Comments

1

You are using exactly the same search space on each iteration. Also, you need to stop when high - low < 2, otherwise mid will eventually equal low, and you might still be stuck in an infinite loop.

As an aside, you can get mid more simply: (low + high)/2.

Comments

1

Hint: In the 2 return BinarySearch() calls, you keep calling it with the same parameters, so it keeps looping to the same spot on the next call, which keeps calling with the same parameters...

This is really a homework question. Hint Ends.

Comments

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.