Python 简单的实现二分查找

系统 210 0
            
              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)


            
          

更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请请扫描上面二维码支持博主1元、2元、5元等您想捐的金额吧,狠狠点击下面给点支持吧

发表我的评论
最新评论 总共0条评论