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
lenik
23.6k4 gold badges38 silver badges44 bronze badges
1 Answer 1
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)
answered Sep 23, 2019 at 2:10
lenik
23.6k4 gold badges38 silver badges44 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py
ctrl-k. Formatting help ... more Formatting ... Formatting sandboxhigh,low, andmiddle_termare indices.data[middle_term]is a value at an index. you are keeping track of indices not values.high = data[middle_term] -1.