python基础--二分查找

时间:2024-04-02 14:07:44
# 二分查找

def sort_search(lst,key):
"""
二分查找
:param lst: 有序数列
:param key: 要查找的关键值
:return: key在数列中的索引
"""
low, high = 0, len(lst)-1
while low < high:
mid = (low + high)//2
if lst[mid] < key:
low = mid + 1
elif lst[mid] > key:
high = mid - 1
else:
return mid
return None l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print('key index:',sort_search(l,80))