In order to solve your problem you need to check the value at the middle position (medio
) not the calculated middle index itself. Then your program will return the correct result.
Additionally you could do some things to improve your program:
- your
break
statement is unreachable as the return
statement is before it, so you should remove it from your code
for
loops are usually used to iterate over all items e.g. of a list. For iterating until a condition is met, one usually uses a while
loop. It's more natural and makes reading the code a lot easier.
- This is more of a theoretical point and does not really apply to Python (See SO Question - Integer overflow in Python3) but I wanted to include it anyway as it is something to generally consider when programming (in other languages): Your approach to calculating the middle could (theoretically) fail for two large integers as the result would overflow. You can use another approach which is not prone to this kind of problem by calculating the middle index using subtraction.
peso = [1, 4, 6, 7, 34, 323, 4333]
def binary_search(to_be_found):
left = 0
right = len(peso) - 1
while left < right:
middle = (right - left) // 2
if peso[middle] < userInput:
right = middle - 1
elif peso[middle] > userInput:
left = middle + 1
else:
return middle
return -1
userInput = int(input("Please enter element to be found"))
print(binary_search(userInput))