Commit e85ddb0c by BellCodeEditor

save project

parent 93787f28
Showing with 8 additions and 8 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]
lxy = 0 def binary_search(alist,num):
dsq = len(num_list) - 1 lxy = 0
while True: dsq = len(alist) - 1
while True:
mid = (lxy + dsq) // 2 mid = (lxy + dsq) // 2
guess = num_list[mid] guess = alist[mid]
if guess == 20: if guess == num:
print("找到了") return mid
break
elif dsq < lxy: elif dsq < lxy:
print("没有这个内容") print("没有这个内容")
break break
elif guess < 20: elif guess < num:
lxy = mid + 1 lxy = mid + 1
else: else:
dsq = mid - 1 dsq = mid - 1
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