二分查找

2018-04-20  本文已影响0人  胖虎很可爱

递归

def binary_search(alist, item):
    """二分查找,递归"""
    n = len(alist)
    if n > 0:
        mid = n//2
        if alist[mid] == item:
            return True
        elif item < alist[mid]:
            return binary_search(alist[:mid], item)
        else:
            return binary_search(alist[mid+1:], item)
    return False

非递归

def binary_search_2(alist, item):
    """二分查找, 非递归"""
    n = len(alist)
    first = 0
    last = n-1
    while first <= last:
        mid = (first + last)//2
        if alist[mid] == item:
            return True
        elif item < alist[mid]:
            last = mid - 1
        else:
            first = mid + 1
    return False

二分查找的时间复杂度

最优情况:O(1)

最差情况O(logn)

上一篇下一篇

猜你喜欢

热点阅读