二分查找的循环和递归Python实现
程序员文章站
2024-03-19 21:36:16
...
二分查找的前提是数组或列表有序,下面以升序列表为例,key为要查找的关键字,查找成功返回下标,不成功返回None,给出循环和递归实现。
循环实现:
def HalfSearch(OrderedList, key, left, right):
while left <= right:
mid = (left + right) // 2
if key == OrderedList[mid]:
return mid
elif key > OrderedList[mid]:
left = mid + 1
else:
right = mid - 1
return None
递归实现:
def HalfSearch(OrderedList, key, left , right):
if left > right:
return None
mid = (left + right) // 2
if key == OrderedList[mid]:
return mid
elif key > OrderedList[mid]:
return HalfSearch(OrderedList, key, mid + 1, right)
else:
return HalfSearch(OrderedList, key, left, mid - 1)
上一篇: 有趣的python排序模块:bisect
下一篇: 二分查找递归与循环实现