我想进行二进制搜索,但结果有问题

时间:2019-08-16 07:37:19

标签: 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))

3 个答案:

答案 0 :(得分:2)

您可以使用以下方式编写脚本:

  1. 将元素放在列表的中间
  2. 如果需要的话退还
  3. 如果您的needle位于中间,则请在列表的其余右侧调用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所述,您必须将列表递归地分成两半

答案 1 :(得分:1)

请经历以下步骤:

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 newl[check] > a:              #fixed the bug here
        for x in newl[:check]:
            if x == a:
                return True

    if newl[check] < a:             #fixed the bug here
        for x in newl[check:]:
            if x == a:
                return True

    return False        #Return false should be universal. When the entire search fails it should be called.

print(clist(7))

答案 2 :(得分:0)

您的函数不是二进制搜索,您要在检查中间元素之后逐个检查排序列表中的元素。

def binary_search(arr, i):
    n = len(arr)
    arr = sorted(arr)
    left = 0
    right = n - 1

    # Define the condition when the loop should be broken 
    while (left <= right):
        mid = left + (right-left) // 2
        if arr[mid] == i:
            return True
        elif arr[mid] < i:
            left = mid + 1 
        else:
            right = mid - 1
    return False

l = [2,6,5,9,7,1,4,8,3]
i = 7
binary_search(l, i)