Commit 94494e3f by BellCodeEditor

save project

parent d8c05873
Showing with 26 additions and 19 deletions
# 使用二分查找法,找出9和20在列表里面的索引 # 使用二分查找法,找出9和20在列表里面的索引
num_list = [1, 3, 5, 8, 11, 15, 17, 18, 20, 21] import random
num = 20 alist = []
low = 0 for i in range(1,101):
high = len(num_list)-1 alist.append(i)
num = random.choice(alist)
while high >= low: def binary_search(alist,num):
mid = (low + high)//2 high = len(alist)-1
low = 0
while high >= low:
mid = (low + high)//2
guess = num_list[mid] guess = alist[mid]
if guess == num: if guess == num:
print("找到了") print("找到了")
print(mid) return mid
break
elif guess < num: elif guess < num:
low = mid+1 low = mid+1
elif guess > num: elif guess > num:
high = mid-1 high = mid-1
if high < low: if high < low:
print("没有这个数") print("没有这个数")
\ No newline at end of file
g = binary_search(alist,num)
print(g)
\ 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