1

Wrote this code in comp sci class and I cant get it to work. Its supposed to be a recursive binary search method... Any idea why I can't get it to work?

 arr = [1,10,12,15,16,122,132,143,155]

def binarysearch(arr,num):
    arr2 = []
    for i in range (len(arr)/2):
        arr2.append(0)
    if (arr[len(arr)/2]>num):
        for x in range (len(arr)/2,len(arr)):
            arr2[x-(len(arr)/2)]=arr[x]
        binarysearch(arr2,num)
    if(arr[len(arr)/2]<num):
        for x in range(0, len(arr) / 2 ):
            arr2[x] = arr[x]
        binarysearch(arr2, num)
    if(len(arr)==1):
        if(arr[0]==num):
            return 1
        else:
            return 0


num = raw_input("put number to check here please: ")
if(binarysearch(arr,num)==1):
    print "true"
else:
    print "false"
4
  • At a glance, your first two if blocks look suspicious to me. When you recursively call a function, if you want both calls to terminate when the inner call returns, then you need a return statement: return binarysearch(arr2,num) Commented Mar 8, 2018 at 14:31
  • Related reading: Why does my function return None? Commented Mar 8, 2018 at 14:33
  • You should probably clarify what you mean by "it doesn't work". Commented Mar 8, 2018 at 14:34
  • I'm not sure why you are creating a new array and appending to that for a binary search. Here's a neat solution - stackoverflow.com/a/46080558/6089653 Commented Mar 8, 2018 at 15:08

0

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.