二分查找算法python实现
作者:互联网
二分查找算法:
用于在有序数组中快速查找所需要的值,前提是数组已经排序
python代码实现:
def binary_search(thelist, item):
low = 0
high = len(thelist) - 1
while low <= high:
mid = int((low + high) / 2)
if thelist[mid] == item:
return mid
elif thelist[mid] < item:
low = mid + 1
else:
high = mid -1
return None
验证算法:
l = [1, 2, 4, 8, 9, 10]
print("the index of result: " + str(binary_search(l, 8)))
l = [1, 2, 4, 8, 9, 10]
print("the index of result: " + str(binary_search(l, 12)))
Robot647
发布了5 篇原创文章 · 获赞 1 · 访问量 47
私信
关注
标签:二分,binary,search,thelist,python,算法,查找,result 来源: https://blog.csdn.net/m0_46245938/article/details/104133746