使用Python进行二进制搜索

时间:2016-12-24 14:41:38

标签: python search binary

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

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]   输入数字:   如果说E.g我给输入25这给了我无限循环......

2 个答案:

答案 0 :(得分: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")

希望这有助于你:)

答案 1 :(得分: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")