Commit 8a7ab08b by BellCodeEditor

auto save

parent b250abfe
Showing with 17 additions and 2 deletions
# 使用二分查找法,找出9和20在列表里面的索引
num_list = [1, 3, 5, 8, 11, 15, 17, 18, 20, 21]
\ No newline at end of file
num_list = [1, 3, 5, 8, 11, 15, 17, 18, 20, 21]
low = 0 #最小值的索引
high = len(num_list)-1 #最大值的索引
num = int(input("值:")) #输入要查找的值
while True: #循环
mid = (low + high)//2 #找到中值的索引
if num == num_list[mid]:#判断中值是否等于要查找的值
print(mid) #输出索引
break #终止循环
elif num > num_list[mid]: #如果中值小于要查找的值
low = mid + 1 #改变最小值的索引
else: #如果中值大于要查找的值
high = mid - 1 #改变最大值的索引
if low > high: #最小值索引大于最大值
print("列表中没有该元素!") #输出
break 终止循环
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment