2016-12-24 79 views
-1

我已经尝试了以下Python算法的二进制搜索,这是给我错误的连续循环时搜索值不在列表中,它应该只是简单地给o/p为“找不到”,我尝试的另一种方法是功能运行良好,但功能不允许使用,我没有得到错误的地方?使用Python的二进制搜索

M = [4,5,6,7,8,9,20,17,45] 
print(M) 
num = int(input("enter the number: ")) 
k=True 
low=0 
high=len(M)-1 
mid=(low-high)//2 
while low<=high: 
print(mid) 
if num == M[mid]: 
    print("Number found") 
    k=False 
    break 
else: 
    if num < M[mid]: 
     high = mid 
     mid = (low+high)//2 
     k=True 

    else: 
     low=mid 
     mid=(mid+high)//2 
     k=True 

if k==True: 
    print("not found") 

在O/P显示

当[4,5,6,7,8,9,20,17,45] 输入号码: 如果说对于例如I给输入25这是给我无限循环......

+0

你压痕不好:'而低<=高:'无关后缩进,在'break'语句不是在一个循环等,请向我们展示代码实际上给你你说的结果。请参见[如何创建最小,完整和可验证示例](http://stackoverflow.com/help/mcve)。通过从原始源代码复制粘贴来正确地设置代码的格式,然后突出显示代码并单击编辑器中的“{}”按钮。 –

回答

1

嘿有你的代码犯了一些错误,

M = [4,5,6,7,8,9,20,17,45] # Your list is not sorted properly 
M.sort() 
print(M) 
num = int(input("enter the number: ")) 
k=True 
low=0 
high=len(M)-1 
mid=(low+high)//2 # you used (low-high) which is not the way to find the mid value 
while low<=high: 
print(mid) 
if num == M[mid]: 
    print("Number found") 
    k=False 
    break 
else: 
    if num < M[mid]: 
     high = mid - 1 # don't need to consider the mid value again 
     mid = (low+high)//2 
     k=True #you don't need to use this statement every loop 

    else: 
     low=mid + 1 # no need to consider mid again 
     mid=(low+high)//2 # should be low not mid 
     k=True 

if k==True: 
    print("not found") 

希望这有助于你:)

0
M = [4,5,6,7,8,9,20,17,45] 
M.sort() # added sort 
print(M) 

num = int(input("enter the number: ")) 
k=True 
low=0 
high=len(M)-1 

while low<high: 
    mid=(high+low)//2 # better place for mid calculating 

    if num == M[mid]: 
    print("Number found") 
    k=False # one k is enough in this while 
    break 
    else: 
    if num < M[mid]: 
     high = mid-1 # you don't need to recheck the mid value in future 
    else: 
     low = mid+1 # you don't need to recheck the mid value in future 

if k==True: 
    print("not found")