简体   繁体   English

当元素不在列表中时,为什么我的二分搜索功能不会停止?

[英]Why my binary search function doesn't stop when the element isn't in the list?

I have the following binary search function:我有以下二进制搜索功能:

def in_bisect(sorted_list, target):

    temp = sorted_list[:]
    low = 0 
    mid = (len(temp)-1) // 2 
    high = len(temp)-1 
    count = 0
    
    if target > temp[high] or target < temp[low]:
        return False
    
    while True:
        mid = len(temp) // 2 
        count += 1
        if target == temp[mid]:
            print("Target found in %d steps " % count)
            return True

        elif target > temp[mid]:  
            low = mid             
            temp = temp[low:]
        
        elif target < temp[mid]: 
            high = mid           
            temp = temp[:high]

    
    return False

It works fine when I look for an element on the given list of words.当我在给定的单词列表中查找元素时,它工作正常。 However, when I test a word that isn't on the list the loop goes to infinite!!!但是,当我测试不在列表中的单词时,循环会无限循环!!!

I have tested it with a list of 113k+ alphabetically sorted words, and it is very efficient (or that what I'd like think at least) it finds the target in 17 steps maximum.我已经用 113k+ 个按字母顺序排序的单词列表对其进行了测试,它非常有效(或者至少我想这样认为)它最多可在 17 个步骤中找到目标。

This is a test I did :这是我做的一个测试:

if __name__ == '__main__':
    fin = open('words.txt')
    a = []
    for line in fin:
        a.append(line.strip())
    print(in_bisect(a,'longsome'))

'longsome' is a word in words.txt file, if I change it to let's say 'blahblah' the loop goes for ever. 'longsome'words.txt文件中的一个词,如果我将它更改为让我们说'blahblah'循环将永远进行。

I would like it to return False immediately if there is no match.如果没有匹配项,我希望它立即返回False Also, any improvement suggestions along the way is appreciated, thanks.此外,感谢沿途的任何改进建议,谢谢。

There was no way for the while loop to break, so until we run out of the range to search for, we go on, otherwise, we break. while 循环没有办法中断,所以直到我们用完要搜索的范围,我们继续,否则,我们中断。 Also, low = mid + 1 was required as otherwise the list size won't reduce properly.此外, low = mid + 1是必需的,否则列表大小将无法正确减小。 Same for high . high

def in_bisect(sorted_list, target):

    temp = sorted_list[:]
    low = 0 
    mid = (len(temp)-1) // 2 
    high = len(temp)-1 
    count = 0
    
    if target > temp[high] or target < temp[low]:
        return False
    
    while True:
        if len (temp) == 0:
            break
        mid = len(temp) // 2
        count += 1
        if target == temp[mid]:
            print("Target found in %d steps " % count)
            return True

        elif target > temp[mid]:  
            low = mid + 1             
            temp = temp[low:]
        
        elif target < temp[mid]: 
            high = mid - 1           
            temp = temp[:high + 1]

    
    return False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM