其他分享
首页 > 其他分享> > 6-有序表二分查找法

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))

标签:二分,log,复杂度,alist,binarySearch,查找,有序,first
来源: https://www.cnblogs.com/lotuslaw/p/13968783.html