【问题标题】:Binary Search Not Finding Certain Numbers二进制搜索未找到某些数字
【发布时间】: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

我无法弄清楚为什么会这样。很确定是我很愚蠢,但如果有人能提供帮助,我将不胜感激!

干杯,

【问题讨论】:

    标签: python-3.x binary-search


    【解决方案1】:

    我无法与算法的其余部分交谈,但middle_index 的计算不正确:

    middle_index = int((end_index - start_index) / 2)
    

    例如start_index = 5end_index = 7,则计算出的middle_index1,此时应为6

    首先,您需要将start_index 添加到该范围大小计算中:

    middle_index = start_index + int((end_index - start_index) / 2)
    

    【讨论】:

    • 我同意极好的雨,因为我不太明白你的意思。 @fbrereto,你能给我看一个代码示例吗?
    猜你喜欢
    • 2020-05-14
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 2013-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多