Commit 41071244 by BellCodeEditor

auto save

parent c7faa222
Showing with 14 additions and 14 deletions
# 使用二分查找法,找出9和20在列表里面的索引 # 使用二分查找法,找出9和20在列表里面的索引
a_num=20 a_num=20#要查找的数字
num_list = [1, 3, 5, 8, 11, 15, 17, 18, 20, 21,32,64] num_list = [1, 3, 5, 8, 11, 15, 17, 18, 20, 21,32,64]#列表
low=0 low=0#最小的索引
high=len(num_list)-1 high=len(num_list)-1#最高的索引列表数值减一
while low<=high: while low<=high:重复执行直到最小的小于等于最高的
mid=(low+high)//2#向下取整 mid=(low+high)//2#向下取整
guess=num_list[mid] guess=num_list[mid]#取出中间值
if guess==a_num: if guess==a_num:#如果取得中间值等于需要的数值
print("找到了他的索引是",mid) print("找到了他的索引是",mid)#那么打印找到了索引在。。
break break#退出循环
elif guess<a_num: elif guess<a_num:#否则如果中间值小于需要的数值
low=mid+1 low=mid+1#最低等于中间索引值加1
else: else:#否则中间值大于需要的数值
high=mid-1 high=mid-1#最大索引等于中间索引值减1
\ No newline at end of file \ No newline at end of file
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