Python 简单的实现二分查找

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)

你可能感兴趣的:(Python)