欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

binary search in Python

程序员文章站 2022-05-05 19:10:43
...

binary search

def binary_search(list_02, item):
    n = len(list_02)
    if n >= 1:
        mid = n // 2
        if list_02[mid] == item:
            return True
        elif item < list_02[mid]:
            return binary_search(list_02[:mid], item)
        else:
            return binary_search(list_02[mid + 1:], item)
    else:
        return False


def binary_search_02(list_02, item):
    n = len(list_02)
    first = 0
    last = n - 1
    while first <= last:
        mid = (first + last) // 2
        if list_02[mid] == item:
            return True
        elif item < list_02[mid]:
            last = mid - 1
        else:
            first = mid + 1
    return False

def main():
    list_01 = [1, 2, 4, 6, 19, 28, 48, 54, 55, 65, 95]
    print(binary_search(list_01, 55))
    print(binary_search(list_01, 155))
    print(binary_search_02(list_01, 55))
    print(binary_search_02(list_01, 155))

if __name__ == '__main__':
    main()


---------------results of enforcement----------
True
False
True
False

-----------------------------------------------
相关标签: Python