Loading

7-有序表二分查找法-分而治之-递归策略

# 由于二分查找,每次比对都将下一步的比对范围缩小一半,n次比对后剩余数据n/2**i,求出i=log2(N)

def binarySearch(alist, item):
    if len(alist) == 0:
        return False
    else:
        midpoint = len(alist) // 2
        if alist[midpoint] == item:
            return True
        else:
            if item < alist[midpoint]:
                return binarySearch(alist[:midpoint], item)
            else:
                return binarySearch(alist[midpoint+1:], item)

testlist = [2, 3, 3, 23, 24, 243, 24455]
print(binarySearch(testlist, 34))
print(binarySearch(testlist, 23))
posted @ 2020-11-13 12:57  lotuslaw  阅读(316)  评论(0编辑  收藏  举报