Commit 4fd6b3b9 by BellCodeEditor

auto save

parent b860994f
Showing with 12 additions and 20 deletions
# 使用二分查找法,找出9和20在列表里面的索引 # 使用二分查找法,找出数字在列表里面的索引
num_list = [1,3,5,8,11,15,17,18,20,21] num_list = [1,3,5,8,11,15,17,18,20]
low = 0 low = 0
high = len(num_list)-1 high = len(num_list)-1
while True: while True:
mid = (low+high)//2 print('输入Q退出程序!')
guess = num_list[mid] number = input('请输入要寻找的数:')
if guess == 20: if number == Q:
print('找到这个数了!')
print(str(mid))
break break
elif guess < 20: elif number != int:
low = mid+1
else:
high = mid-1
if high <= low:
print('没有这个数!')
break break
low = 0 else:
high = len(num_list)-1 while True:
while True:
mid = (low+high)//2 mid = (low+high)//2
guess = num_list[mid] guess = num_list[mid]
if guess == 9: if guess == int(number):
print('找到这个数了!') print('找到这个数了!')
print(str(mid)) print('这个数在列表中的索引为'+str(mid))
break break
elif guess < 9: elif guess < int(number):
low = mid+1 low = mid+1
else: else:
high = mid-1 high = mid-1
if high <= low: if high <= low:
print('没有这个数!') print('列表中没有这个数!')
break 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