二分查找算法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)))
发布了7 篇原创文章 · 获赞 34 · 访问量 5788

猜你喜欢

转载自blog.csdn.net/m0_46245938/article/details/104133746
今日推荐