Loading

6-有序表二分查找法

# 通过控制列表索引达到二分的目的
# 算法时间复杂度O(log(N))

def binarySearch(alist, item):
    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


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