0

I wrote a code that takes a line of numbers and switch it into a list, sort the list and do the binary search. But if I run the code, it prints out None depending on the input list and the value target. For instance, if my_list = [5, 4, 3, 2, 1] and target = 2 or my_list = [8, 4, 5, 1, 3, 52, 39] and target = 8, the result is like this picture I uploaded. How could I fix this error??

def binary_search(arr, first, last, target):
    if last >= first:
        middle = (first + last) // 2

        if arr[middle] == target:
            return middle

        elif arr[middle] < target:
            binary_search(arr, middle + 1, last, target)

        else:
            binary_search(arr, first, middle - 1, target)
    else:
        return -1

my_list = [int(i) for i in input().split(' ')]
target = int(input())
my_list.sort()

print(my_list)

result = binary_search(my_list, 0, len(my_list) - 1, target)
print(result)

0 Answers0