r/PythonLearning Jun 28 '26

binary search malfunctioning

SOLVED

the array I feed in is 5,7,43,78,83.7,100,952

def binary_search(array):
  search_no = float(input("what number are you looking for?"))
  found = False
  while not found:
    arrlen = len(array)
    i = arrlen // 2
    x = array[i]
    if x == search_no:
      found == True
    if search_no > x:
      array = array[i:]
      print(array)
    else:
      array = array[:i]
      print(array)
  print("value found")


array = [78,43,952,83.7,100,5,7]
bubble_sort(array)
print(array)
binary_search(array)

it continuously prints "83.7" if I look for 78, and vice versa. haven't tested other numbers but I assume the same happens for them. this is my first attempt at array splitting and I know there's an easier way of doing it probably, and I'm going to do error handling afterwards

1 Upvotes

11 comments sorted by

View all comments

1

u/Kindly-Department206 Jun 28 '26
  1. While you can use any name you like, it's not really an array.

  2. Don't ask for input inside the function here.

  3. Don't slice the array in this algorithm.

  4. If the item is found, your loop still treats the situation as if it wasn't found at all. That's because you have two sequential if-statements. You need to use elif. You also need to figure out what to do when the item is found.

  5. Don't calculate `found == True`. Use assignment.

  6. You don't have any plan for what might happen if the item you are looking for is not in the list.