折半查找python代码实现

ls = [i+1 for i in range(11)]

i = 0

def binary_search(value, front, end):
    global i
    i += 1
    mid = (front + end)//2
    if end >= front:              # 这里是大于等于
        if value == ls[mid]:
            print(f"第{i}次查找成功:{ls[mid]}")
        elif value > ls[mid]:
            print(f"第{i}次查找元素:{ls[mid]}")
            front = mid + 1
            mid = (front + end) // 2
            binary_search(value, front, end)
        elif value < ls[mid]:
            print(f"第{i}次查找元素:{ls[mid]}")
            end = mid - 1
            mid = (front + end) // 2
            binary_search(value ,front, end)
    else:
        print("查找失败!")

binary_search(11, 0, len(ls)-1)
posted @ 2023-08-14 23:14  小默同学  阅读(27)  评论(0编辑  收藏  举报