Commit 41071244 by BellCodeEditor

auto save

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