#循环二分查找
def binarySearch(alist, key):
left = 0
right = len(alist) - 1
found = False
while left < right and not found:
mid = (left + right) // 2# 整除
if alist[mid] == key:
found = True
else:
if alist[mid] < key:
left = mid + 1
else:
right = mid - 1
if found:
return mid
else:
return -1
# 递归二分查找,利用列表切片来缩小规模
def binarySearch1(alist, key):
if len(alist) == 0:# 递归出口,当列表中没有元素时,查找失败
return -1
mid = len(alist) // 2
if alist[mid] == key:
return mid
else:
if alist[mid] < key:
return binarySearch1(alist[mid+1:], key)
else:
return binarySearch1(alist[:mid], key)
python实现二分查找
最新推荐文章于 2024-04-17 21:49:47 发布