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

问题描述

我具有以下二进制搜索功能:

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

当我在给定单词列表中寻找元素时,它可以正常工作。但是,当我测试不在列表中的单词时,循环将变为无限!!

我已经用113k +字母排序的单词列表对其进行了测试,它非常有效(或者至少我想以这种方式),它最多可以17个步骤找到目标。

这是我做过的测试:

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

'longsome'words.txt文件中的一个词,如果我将其更改为'blahblah',则循环永远存在。

如果没有匹配项,我希望它立即返回False。 另外,感谢您在此过程中提出的任何改进建议。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)