Commit c41dfe9f by BellCodeEditor

auto save

parent c30301f6
Showing with 17 additions and 11 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]
num = 9
low = 0 def binary_search(alist,num):
high = len(num_list)-1 low = 0
mid = (low+high)//2 high = len(num_list)-1
if num_list[mid]==num: while low<=high:
print("找到了,它在列表里的索引为:"+mid) mid = (low+high)//2
elif num_list[mid]<num: guess = alist[mid]
low = mid+1 if guess == num:
else: return mid
high = mid-1 elif guess < num:
\ No newline at end of file low = mid + 1
elif guess > num:
high = mid - 1
return None
resalt = binary_search(num_list,20)
print(resalt)
\ 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