二分法

自调用函数的二分法

data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35]
def binary_search(dataset,find_num):
    if len(dataset) > 1:
        mid = int(len(dataset) / 2)
        if dataset[mid] == find_num:  # find it
            print("找到数字", dataset[mid])
        elif dataset[mid] > find_num:  # 找的数在mid左面
            print("33[31;1m找的数在mid[%s]左面33[0m" % dataset[mid])
            return binary_search(dataset[0:mid], find_num)
        else:  # 找的数在mid右面
            print("33[32;1m找的数在mid[%s]右面33[0m" % dataset[mid])
            return binary_search(dataset[mid + 1:], find_num)
    else:
        if dataset[0] == find_num:  # find it
            print("找到数字啦", dataset[0])
        else:
            print("没的分了,要找的数字[%s]不在列表里" % find_num)
binary_search(data,20)
# 输出结果
找的数在mid[18]右面
找的数在mid[30]左面
找的数在mid[22]左面
找的数在mid[21]左面
找到数字啦 20

while循环的二分法

def binary_search(li,val):
    left = 0
    right= len(li)-1
    while left <= right:
        mid = (left+ right)//2
        if li[mid] > val: #val 在 mid的左边
            right = mid-1
        elif li[mid]< val:
            left = mid +1
        else:
            print(mid)
            return mid
    else:
        print('此列表中没有要查找的值')
        return None
写入自己的博客中才能记得长久
原文地址:https://www.cnblogs.com/heris/p/14032625.html