Python 实现二分查找
"""
二分查找,在有序列表基础上
bisect 模块
"""
# 普通方式
def binary_search(sorted_array, val):
if not sorted_array:
return -1
beg = 0
end = len(sorted_array) - 1
while beg <= end:
mid = int((beg + end)/2)
if sorted_array[mid] == val:
return mid
elif sorted_array[mid] > val:
end = mid - 1
else:
beg = mid + 1
return -1
# 递归实现二分
def binary_search_recursive(sorted_array, beg, end, val):
if beg >= end:
return -1
mid = int((beg + end) / 2)
if sorted_array[mid] == val:
return mid
elif sorted_array[mid] > val:
return binary_search_recursive(sorted_array, beg, mid, val)
else:
return binary_search_recursive(sorted_array, mid+1, end, val)
print(binary_search_recursive([2,3,4], 0, 3, 4))
作者:皎然CEO
链接:https://www.cnblogs.com/jiaoran/p/14584302.html
个性签名:独学而无友,则孤陋而寡闻。做一个灵魂有趣的人!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦(っ•̀ω•́)っ✎⁾⁾!