python 代码实现二分查找(非递归版本)
程序员文章站
2024-03-19 14:57:34
...
def binary_search(alist, item):
'''二分查找'''
n = len(alist)
first = 0
last = n -1
while first <= last:
mid = (first+last)//2#中间位置下标获取很关键
if alist[mid] == item:
return True
elif item < alist[mid]:
last = mid-1
else:
first = mid +1
return False
if __name__ == '__main__':
li = [0, 5, 8, 10, 65, 99, 100]
print(binary_search(li, 99))
print(binary_search(li, -1))
C:\Users\user\AppData\Local\Programs\Python\Python36\python.exe “C:/Users/user/PycharmProjects/hellow python/test.py”
True
False
Process finished with exit code 0