二进制搜索应该不工作

时间:2017-01-05 22:41:12

标签: python list python-3.x binary-search

我有一个二进制搜索,用于搜索给定电子邮件输入的用户列表。我没有错误,我没有得到任何输出。我无法看出它出了什么问题?

def BubbleSort(logindata):
    NoSwaps = 1
    N = len(logindata)
    logindata = list(logindata)
    while NoSwaps == 1:
        Count = 1
        NoSwaps = 0
        for Count in range(N-1):
            if logindata[Count] > logindata[Count+1]:
                temp = logindata[Count]
                logindata[Count] = logindata[Count+1]
                logindata[Count+1]=temp
                NoSwaps=1
    return tuple(logindata)

def BinarySearch(logindata,ItemSought):
    First=0
    Last=len(logindata)-1
    ItemFound = False
    SearchFailed = False
    while ItemFound == False or SearchFailed == False:
        Midpoint = (First + Last) // 2
        if logindata[Midpoint] == ItemSought:
            print("Item Found")
            ItemFound = True
            print("Item Found")
            break

        elif logindata[Midpoint][0] > ItemSought:
            Last = Midpoint - 1

        else:
            First = Midpoint + 1


if __name__ == "__main__":
    logindata=["tom@gmail.com","Password1"],["harry@gmail.com","Password2"],["jake@gmail.com","Password3"]
    logindata=BubbleSort(logindata)
    print(logindata)
    ItemSought=input("Enter username")
    BinarySearch(logindata,ItemSought)

2 个答案:

答案 0 :(得分:2)

if logindata[Midpoint] == ItemSought:

将列表与字符串进行比较。所以我认为你需要

 if logindata[Midpoint][0] == ItemSought:

答案 1 :(得分:0)

您永远不会终止搜索。如果项目不在列表中,您将获得稳定的中点并无限循环。如果你确实找到了这个项目,你可以无限循环 (参见Yehven的回答)。

我用你在这里看到的补充来追踪它:

SearchFailed = False
iter = 0
while iter < 10 and (ItemFound == False or SearchFailed == False):
    iter += 1
    Midpoint = (First + Last) // 2
    print (First, Midpoint, Last, ItemSought)
    if logindata[Midpoint] == ItemSought:

请注意,您无法更改 SearchFailed 。例如,当我搜索&#34; harry&#34;时,循环在(0,-1,-2)处为第一,中,最后一个稳定的无限点。

这是否足以让你自己修复它?