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"
fleetingbytes
  • 2,512
  • 5
  • 16
  • 27
ItsDembo
  • 13
  • 3
  • 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)` – Kevin Mar 08 '18 at 14:31
  • Related reading: [Why does my function return None?](https://stackoverflow.com/questions/17778372/why-does-my-function-return-none) – Kevin Mar 08 '18 at 14:33
  • You should probably clarify what you mean by "it doesn't work". – Garrett Gutierrez Mar 08 '18 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 - https://stackoverflow.com/a/46080558/6089653 – nj2237 Mar 08 '18 at 15:08

0 Answers0