二分查找

二分查找要求数组必须有序,代码比较容易理解

如下:

# coding: utf-8

arr1 = [0, 1, 3, 5, 7, 8]
item = 3


# non-recurse
def binary_search(alist, aitem):
    n = len(alist)
    start = 0
    end = n - 1
    while start <= end:
        mid = (start + end) // 2
        if alist[mid] == aitem:
            return True
        elif aitem < alist[mid]:
            end = mid - 1
        else:
            start = mid + 1
    return False


print(binary_search(arr1, item))


# recurse
def binary_search_recurse(alist, aitem):
    n = len(alist)
    if n == 0:
        return False
    mid = n // 2
    if aitem == alist[mid]:
        return True
    elif aitem < alist[mid]:
        return binary_search_recurse(alist[:mid], aitem)
    else:
        return binary_search_recurse(alist[mid + 1:], aitem)


print(binary_search_recurse(arr1, item))

你可能感兴趣的:(二分查找)