python实现二分查找(递归与非递归)

1,二分查找(非递归算法)

def binary_search_3(alist,item):
    """
    二分法查找
    :param alist:
    :param item:
    :return:
    """
    start = 0
    end = len(alist)-1
    while start <= end:
        mid = (start + end)//2
        if item == alist[mid]:
            return True
        elif item > alist[mid]:
            start = mid + 1
        else:
            end = mid - 1
    return False

if __name__ =='__main__':
    testlist=[0, 1, 2, 8, 13, 17, 19, 32, 42]
    print(binary_search_3(testlist,17))
    print(binary_search_3(testlist,19))在这里插入代码片

时间复杂度

  • 最优时间复杂度:O(1)
  • 最坏时间复杂度:O(logn)

2,二分查找(递归算法)

def binary_search(alist,item):
    """二分查找,递归实现版本"""
    n = len(alist)
    if 0 == n:
        return False
    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)

if __name__ == '__main__':
    testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42]
    print(binary_search(testlist, 32))
    print(binary_search(testlist, 60))

你可能感兴趣的:(数据结构,python,算法)