python - 为什么这个二分搜索算法两次返回 None ?

标签 python algorithm binary-search

我开始学习算法(使用 grokkings 算法书),这是书中的二分搜索代码

def binary_search(list, item):

  low = 0
  high = len(list) - 1

  while low <= high: 
    mid = round((low + high) )
    guess = list[mid]
    
    if guess == mid:
      return mid

    if guess > mid: 
      high = mid - 1 

    else: 
      low = mid + 1

  return None

my_list = [1, 3, 5, 7, 9]

print(binary_search(my_list, 3))
print(binary_search(my_list, -1))

第一个应该返回 1 但它返回 None 两次,有人知道为什么吗?

最佳答案

尝试将猜测项目进行比较:

def binary_search(lst, item):
    low = 0
    high = len(lst) - 1
    while low <= high: 
        mid = (low + high) // 2
        guess = lst[mid]
        if guess < item:
            low = mid + 1
        elif guess > item: 
            high = mid - 1
        else:
            return mid
    return None


my_list = [1, 3, 5, 7, 9]
print(binary_search(my_list, 3))
print(binary_search(my_list, -1))

输出:

1
None

关于python - 为什么这个二分搜索算法两次返回 None ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71029145/

相关文章:

javascript - 将两个排序数组合并为一个

c++ - 最接近值的二进制搜索 vector C++

python - 如何检查字典中是否存在具有特定模式的值?

python - 打印 [Python] 在 Pycharm 中被视为关键字

c++ - std::sort 过火了

c - 二进制搜索单词词典

c - 使用字符数组进行二进制搜索?

python - 在 pandas 数据框中选择遵循特定模式的行

python - Django cursor.executemany 参数

algorithm - 当集合不相交时,是否有类似于联合查找的交集查找算法?