二分查找算法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)))

你可能感兴趣的:(算法)