下面的python代码似乎运行良好如果我按照注释修改代码,它似乎仍然有效如果我使用high = middle而不是high = middle - 1low = middle而不是low = middle + 1,算法会失败吗?

haystack = [3,5,7,8,9,23,65,89,100]
needle = 89
low = 0
high = len(haystack)

while (low < high):
  middle = (high + low)//2
  if (needle < haystack[middle] ):
     high = middle - 1 # what about just high = middle?
  elif (needle > haystack[middle]):
    low = middle + 1 # what about just low = middle?
  elif (needle == haystack[middle]):
    print ("The needle was found at index " + str (middle))
    break

最佳答案

这是因为您只考虑值在列表中的情况(可能有一个列表包含元素的情况,需要这些行,但我想不出一个)
想想下面的简单例子:

haystack = [1,2]
needle = 3
the rest of the code...

如果没有当前版本的代码,您将陷入无限循环。
注意:正如@vivekß23提到的,您已经在检查中间,因此不需要额外的迭代。

关于python - 二进制搜索算法测试重复值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55006719/

10-11 04:22