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

Python 简单的实现二分查找

程序员文章站 2024-03-19 21:35:58
...
def BinarySearch(alist, item):
    '''
    简单二分查找
    :param alist:
    :param item:
    :return:
    '''
    first = 0
    last = len(alist) - 1
    found = False
    while first <= last and not found:
        midpoint = (first + last)//2
        if alist[midpoint] == item:
            found = True
        else:
            if item < alist[midpoint]:
                last = midpoint - 1
            else:
                first = midpoint + 1
    return found

def binarysearch(alist, item):
    '''
    递归二分法
    :param alist: 有序列表
    :param item: 待查询值
    :return: True or False
    '''
    if len(alist) == 0:
        return False
    else:
        middlepoint = len(alist) // 2
        if alist[middlepoint] == item:
            return True
        else:
            if item < alist[middlepoint]:
                return binarysearch(alist[:middlepoint], item)
            else:
                return binarysearch(alist[middlepoint+1:], item)