Commit 831d1737 by BellCodeEditor

auto save

parent b250abfe
Showing with 62 additions and 2 deletions
num_list = [1, 3, 5, 8, 11, 15, 17, 18, 20, 21]
N = len(num_list)
L = 0
H = N - 1
num = 20
while True:
print(L,H)
M = (L + H) // 2
G = num_list[M]
if G == num:
print('找到了,在第' ,M+1 , '个')
break
elif H < L:
print('没找到')
break
elif num < G:
H = M - 1
else:
L = M + 1
\ No newline at end of file
num_list = []
def search(num_list,num):
low=0
high=len(num_list)-1
while True:
mid=(low+high) // 2
if num_list[mid] == num:
return "找到了。在"+str(mid+1)+"个。"
elif low > high:
return "没找到。"
elif num_list[mid] < num:
low=mid+1
else:
high=mid-1
for i in range(1,101):
num_list.append(i)
print(search(num_list,99))
\ No newline at end of file
# 使用二分查找法,找出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]
\ No newline at end of file #求长度,方便最高索引
#求最低索引和最高索引,以及要查找的数据
n = len(num_list)
low = 0
high = n-1 #high = len(num_list) - 1
num = 20
while True:
#中间索引 = (最低索引+最高索引) // 2
print(low,high)
mid = (low+high) // 2
if num == num_list[mid]:
print("找到了,在第",mid+1,'个')
break
elif low > high:
print("没找到")
break
elif num > num_list[mid]:
low = mid + 1
else:
high = mid - 1
\ 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