二分法查找

1.用函数来进行二分查找:

  lst = [11,22,33,44,55,66,77,88,99,123,234,345,456,567,678,789,1111]

def run(left,right,n,count):
middle=(left+right)//2
if n >lst[middle]:
left=middle+1
elif n < lst[middle]:
right=middle-1
else:
return (middle,'找到了,共计查找了%s次' % count)
return run(left,right,n,count+1)
print(run(0,len(lst)-1,11,1))

2.普通方法:

lst = [11,22,33,44,55,66,77,88,99,123,234,345,456,567,678,789,1111]
n=11 #要查询的数
left=0
right=len(lst)-1
count=0
while left <= right:
count+=1
middle = (left + right) // 2
if n > lst[middle]:
left=middle+1
elif n < lst[middle]:
right=middle-1
else:
print('索引为%s,共计查询了%s次' % (middle,count))
break
else:
print('不存在')


posted @ 2018-07-31 10:28  叶落kiss  阅读(179)  评论(0编辑  收藏  举报