binary search in Python

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

-----------------------------------------------

猜你喜欢

转载自blog.csdn.net/Xcq007/article/details/82115698
今日推荐