Reputation: 43
in the conditionals why don't you have to write high = data[middle_term] - 1
. I understand why you do it in the actual if/else statements
data = [1,2,3,6,9,12,15,18,20]
def binary_search_algorthim(data,target):
low = 0
high = len(data) - 1
while low <= high:
middle_term = (low + high) // 2
if target == data[middle_term]:
return True
elif target < data[middle_term]:
high = middle_term - 1
print("high",high)
elif target > data[middle_term]:
low = middle_term + 1
print("low", low)
return False
Upvotes: 1
Views: 170
Reputation: 23498
high
and low
are not the actual numbers from your data, they just mark the place where the actual numbers are, so when you want to compare to target
you don't compare the place and the value, you have to compare the value at the place and the value.
Hence, target
(value) = data[ (position) ]
(again, a value)
Upvotes: 1