Commit d994ba28 by BellCodeEditor

auto save

parent 42d91ab8
Showing with 7 additions and 6 deletions
# 使用二分查找法,找出9和20在列表里面的索引 # 使用二分查找法,找出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, 21]
def check(n): def check(check_list,n):
left = 0 left = 0
right = len(num_list)-1 right = len(check_list)-1
mid = 0 mid = 0
while True: while True:
if right < left: if right < left:
return "没有" return "没有"
mid = (left+right)//2 mid = (left+right)//2
num = num_list[mid] num = check_list[mid]
if num == n: if num == n:
return left return mid
elif num < n: elif num < n:
left = mid+1 left = mid+1
else: else:
right = mid-1 right = mid-1
print(check(20))
\ No newline at end of file print(check(num_list,11))
\ 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