使用python实现二分法查找
程序员文章站
2024-03-16 09:32:22
...
二分法实现快速查找
def bin_search(items,key):
start,end = 0,len(items)-1
while start<=end:
mid =(start+end)//2
if key == items[mid]:
return mid
elif key >items[mid]:
start=mid+1
else:
end=mid-1
return -1
def main():
items = [12,25,33,56,78,89,91]
print(bin_search(items,55))
print(bin_search(items,89))
if __name__ == '__main__':
main()
上一篇: p-7-8快速排序求第k小元素