-2

My binary search function is able to print the correct value , But it returns None Value , why ?

Here is link to code. https://github.com/amitsuneja/AppliedAICourse/blob/master/ExtraCodes/BinarySearchPython.py

from math import floor as fl
import random

def binarysearch(arr, l, r, q):
    if r >= l:
        mid = fl((l + r)/2)
        print("left = ", l)
        print("right =", r)
        print("Current middle of array is :", mid)
        if arr[mid] == q:
            print(" i am here now and mid=", mid)
            return mid
        elif arr[mid] > q:
            binarysearch(arr, 0, mid, q)
        else:
            binarysearch(arr, mid, r, q)
    else:
        return -1

my_List = list(range(50))
random.shuffle(my_List)
my_List.sort()
print("Sort List = ", my_List)
query = 31

result = binarysearch(my_List, 0, len(my_List),query)
if result == -1:
    print("31 not present in list")
else:
    print("index location ", result)

Below is output . First line print the correct index value i.e 31 . But next line prints me None ..Not getting reason when i check variable mid in functions its value is accurate But when i print it using result it return me None.

Output

i am here now and mid= 31

index location  None
DennisLi
  • 3,915
  • 6
  • 30
  • 66
user8588795
  • 321
  • 2
  • 14

1 Answers1

0

You are missing the return statement:

elif arr[mid] > q:
    return binarysearch(arr, 0, mid, q)
else:
    return binarysearch(arr, mid, r, q)
fiveelements
  • 3,649
  • 1
  • 17
  • 16