Commit acec3ccc by BellCodeEditor

auto save

parent b250abfe
Showing with 44 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 = [1, 3, 5, 8, 11, 15, 17, 18, 20, 21, 34, 56, 65, 67, 78, 90]
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)
import random
# 使用二分查找法,找出9和20在列表里面的索引
num_list = [1, 3, 5, 8, 11, 15, 17, 18, 20, 21]
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
if 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