python 递归实现二分查找

def binary_search(alist, item):
    '''二分查找'''
    n = len(alist)
    if n > 0:
        mid = n//2
        if alist[mid] == item:
            return True
        elif alist[mid] > item:
            return binary_search(alist[:mid], item)
        else:
            return binary_search(alist[mid+1:], item)
    else:
        return False

if __name__ == '__main__':
    li = [0, 5, 8, 10, 65, 99, 100]
    print(binary_search(li, 99))
    print(binary_search(li, -1))

C:\Users\user\AppData\Local\Programs\Python\Python36\python.exe “C:/Users/user/PycharmProjects/hellow python/test.py”
True
False

Process finished with exit code 0

你可能感兴趣的:(python)