python3 实现 二分查找

def binary_search(alist, elem):
    '''非递归二分查找'''
    start = 0
    end = len(alist) - 1
    while start <= end:
        mid = (end + start) // 2
        if elem == alist[mid]:
            return mid
        elif elem < alist[mid]:
            end = mid - 1
        else:
            start = mid + 1
    return None

def binary_search2(alist, elem):
    '''递归二分查找'''
    if len(alist) == 0:
        print('False')
    mid = len(alist) // 2
    guess = alist[mid]
    if elem == guess:
        print('True')
    elif elem < guess:
        binary_search2(alist[:mid],elem)
    else:
        binary_search2(alist[mid+1:],elem)

testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42]
binary_search(testlist, 42)
binary_search2(testlist, 42)

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