二分查找


# 参考 https://www.cnblogs.com/longyunfeigu/p/9316082.html
import time

name = 666
index = 0


def x(tmp):
    global index
    length = len(tmp)
    print(index)
    if length >= 2:
        if tmp[length // 2] < name:
            index += length // 2 + 1
            return x(tmp[(length // 2 + 1):])
        elif tmp[length // 2] > name:
            return x(tmp[:length // 2])
        else:
            return index + length // 2
    else:
        print("*********")
        print(tmp)
        for i, v in enumerate(tmp):

            if v == name:
                return index + i + 1
        return 33

def binary_chop(alist, data):
    """
    非递归解决二分查找
    :param alist:
    :return:
    """
    n = len(alist)
    first = 0
    last = n - 1
    while first <= last:
        mid = (last + first) // 2
        if alist[mid] > data:
            last = mid - 1
        elif alist[mid] < data:
            first = mid + 1
        else:
            return True
    return False
if __name__ == '__main__':
    a = [x for x in range(1001)]
    _ = x(tmp=a)
    print(_)

原文地址:https://www.cnblogs.com/lajiao/p/12786255.html