【发布时间】:2020-08-14 06:30:15
【问题描述】:
我正在构建一个二进制数搜索。它旨在查看一系列有序数字以查看给定值是否在其中。
它能够找到一些数字,但偶尔它会进入无限循环或当数字在搜索参数范围内时返回 False。
我目前拥有的代码是:
def binary_search(data_input, user_input):
start_index = 0
end_index = len(data_input) - 1
while True:
middle_index = int((end_index - start_index) / 2)
if user_input > data_input[end_index] + 1 or user_input < data_input[start_index] - 1:
return False
if middle_index > end_index or middle_index < start_index:
return False
middle_element = data_input[middle_index]
if middle_element == user_input:
return True
elif user_input > middle_element:
start_index = middle_index
else:
end_index = middle_index
# I have used this loop to see which numbers create a problem
for i in range(12):
x = 10
data_in = np.arange(x)
user_num = i
print(user_num, binary_search(data_in, user_num))
这个特定循环的结果是:
0 True
1 True
2 True
3 False
4 True
5 False
6 False
7 False
8 False
9 False
10 False
11 False
我无法弄清楚为什么会这样。很确定是我很愚蠢,但如果有人能提供帮助,我将不胜感激!
干杯,
【问题讨论】: