-3

i create a function for binary search and i find the position of searched element but i cannot get the value through the return statement instead of the value it return null

def binary_search(array,low,high,target):
    array.sort()
    print(array)
    # if low <= high:
    mid = (low + high) // 2
    print(low,'-',high)
    print('mid',mid)
    print('mid value',array[mid])

    if array[mid] == target:
        print('yes')
        return mid
    elif array[mid] > target:
        binary_search(array,low,mid-1,target)
    else:
        binary_search(array,mid+1,high,target)
    # else:
    #     return -1
            
    
lis=[2,5,44,66,77,88,99,45,33,47,98,101,105,110,125,134,138,147,156,160,185,155,153,194,178]
lis1 = lis.sort()

print(binary_search(lis,0,len(lis),33)) 
Julien
  • 13,986
  • 5
  • 29
  • 53
Irshad
  • 1

1 Answers1

0

You also need to add return behind each binary_search call since the recursive function call itself return values to the parent function but the parent function doesn't return the value

def binary_search(array,low,high,target):
    array.sort()
    print(array)
    # if low <= high:
    mid = (low + high) // 2
    print(low,'-',high)
    print('mid',mid)
    print('mid value',array[mid])

    if array[mid] == target:
        print('yes')
        return mid
    elif array[mid] > target:
        return binary_search(array,low,mid-1,target)
    else:
        return binary_search(array,mid+1,high,target)
tax evader
  • 2,082
  • 1
  • 7
  • 9