0

I was learning Python for algorithmic purposes. I learned how binary search works and tried to implement it in Python code, without consulting internet. I haven't still looked at how to implement it, I want to make my code work at first. So here is the problem.

The code works fine until the final step where it returns None instead of returning item already in the list. Please instruct me how to correct it. I used pythontutor's online visualizer to visualize the code, and the return value is correct until the final step, where the return value changes to None and I don't understand how. And I also want the "Base case" to return False if item is not in the list and also return the final item (worst case item) at the same time. Please review my code to have these 2 edits.

Here's a link to the code in pythontutor

Below is the code

def binarysearch(array,element):
    mid_index = len(array)//2
    if len(array) == 1 and array[0] == element:
        return element
    elif element == array[mid_index]:
        return element
    elif element > array[mid_index]:
        array = array[mid_index::]
        binarysearch(array,element)
    else:
        array = array[0:mid_index]
        binarysearch(array,element)

print(binarysearch([17,20,26,31,44,54,55,65,77,93],26))
martineau
  • 119,623
  • 25
  • 170
  • 301
Shrijan Aryal
  • 315
  • 1
  • 4
  • 22

0 Answers0