Commit f4a504e9 by BellCodeEditor

auto save

parent b250abfe
Showing with 23 additions and 2 deletions
import random
# 使用二分查找法,找出9和20在列表里面的索引
num_list = [1, 3, 5, 8, 11, 15, 17, 18, 20, 21]
\ No newline at end of file
num_list = []
for i in range(1,100,5):
num_list.append(i)
num = random.choice(num_list)
def binary_search(num_list,num):
low = 0 # 设置最低索引
high = len(num_list)-1 # 设置最高索引
while low <= high: # 无限循环条件 最低索引小于等于最高索引
mid = (low+high)//2 # 找到中间索引
guess = num_list[mid] # 找到你要猜测的数字
if guess == num: # 判断猜测的数字等于你要查找的数字
return mid
elif guess < num: # 否则如果猜测的数字小于查找的数字
low = mid + 1 # 最低索引移到中间索引的右边
else: # 否则
high = mid - 1 # 最高索引移到中间索引的左边
return None
result = binary_search(num_list,num)
print('我们要查找的数字是:',num)
print('它在列表里面的索引是:',result)
\ 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