Python-二分查找法

在这里插入图片描述

list_01 = [2,5,1,4,1,3]

#二分查找/折半查找
#先排序

list_01.sort()
print('首先要对列表进行排序:',list_01)

num = int(input('请输入要查找到数:'))

frist = 0
last = len(list_01)-1

while frist <= last:
    mid = (frist+last)//2  #向下取整
    if list_01[mid] == num:
        print('找到了')
        break
    elif list_01[mid] > num:
        last = mid - 1
    elif list_01[mid] < num:
        frist = mid + 1
else:
print('没找到')

猜你喜欢

转载自blog.csdn.net/Liang_Ren_/article/details/88582372
0条评论
添加一条新回复