python-实现二分查找

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python-实现二分查找相关的知识,希望对你有一定的参考价值。

# 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))

 

以上是关于python-实现二分查找的主要内容,如果未能解决你的问题,请参考以下文章

python实现二分查找与冒泡排序

简单实现一下二分查找

python数据结构与算法第十四天二分查找

二分查找——Python实现

python实现二分查找

python-实现二分查找