python - 我想进行二进制搜索,但结果有误

标签 python binary-search

我想对列表进行二分查找,但即使我检查了列表中的数字,结果仍显示“false”。

def clist(a):

    l = [2,6,5,9,7,1,4,8,3]
    newl = sorted(l)
    check = int(1+len(newl)/2)

    if newl[check] == a:
        return True

    if check > a:
        for x in newl[:check]:
            if x == a:
                return True
            return False

    if check < a:
        for x in newl[check::]:
            if x == a:
                return True
            return False

print(clist(7))

最佳答案

你可以这样写你的脚本:

  1. 取列表中间的元素
  2. 如果这是您需要的,请归还
  3. 如果你的 needle 比中间的 gt,则在列表的剩余右侧调用 bsearch
  4. 否则用左侧调用bsearch
def bsearch(needle, haystack):
    l = len(haystack)
    half = int(l / 2)
    element = haystack[half];

    if element == needle:
        return element

    if needle <= element:
        return bsearch(needle, haystack[0:half])

    if needle > element:
        return bsearch(needle, haystack[half:l])




print(bsearch(7, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))

在二进制搜索中:

  1. 列表必须有序
  2. 如@tripleee 所述,您必须递归地将列表分成两半

关于python - 我想进行二进制搜索,但结果有误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57520637/

相关文章:

python - 具有相同基本名称的 Python 模块、类和实例变量的正确命名约定是什么?

python - 自动化无聊的东西 Collat​​z 项目

.net - 如何对 IList<T> 执行二分查找?

c# - 获取字典中最大的键

python - 给定一个输入字符串,如何在 O(k logN + W) 时间内搜索所有变位词,其中 W 是输出大小,k 是字符串中的最大字符数?

python - 维持某些元素顺序的排列

c++ - 在 Python 中,你如何像 C++ 一样获取标记化输入?

c# - 查找排序数组中的所有差异

python - while 循环不会因多个条件而停止

algorithm - 将 B 个芝士蛋糕分给 N 个类(class),以尽量减少每个蛋糕的最大学生人数