# encoding=utf-8


def binary_search(alist, item):
    """二分查找 非递归方式"""
    n = len(alist)
    start = 0
    end = n-1

    while start <= end:
        mid = (start + end) // 2
        if item == alist[mid]:
            return True
        elif item < alist[mid]:
            end = mid - 1
        elif item > alist[mid]:
            start = mid + 1

    return False


def binary_search2(alist, item):
    """二分查找 递归方式"""
    n = len(alist)
    if 0 == n:
        return False
    mid = n // 2
    if item == alist[mid]:
        return True
    elif item < alist[mid]:
        return binary_search2(alist[:mid], item)
    else:
        return binary_search2(alist[mid+1:], item)


if __name__ == '__main__':
    li = [17, 20, 26, 31, 44, 54, 55, 77, 93]
    # print(binary_search(li, 55))
    # print(binary_search(li, 100))
    print(binary_search2(li, 55))
    print(binary_search2(li, 100))

 

posted on 2017-09-17 00:24  晴空半岛  阅读(990)  评论(0编辑  收藏  举报