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))
上一篇:二分查找


下一篇:二分查找递归解法