def cc(list1,value):
if value in list1:
beg = 0
end = len(list1)
count = 1
while beg <= end:
medain = int((beg+end)/ 2) #例如:第4和第5个下坐标的中间值等于4+5除以2,所以下面要用坐标中间值-1 +1
if l1[medain] == value:
print(f"找到了{value},共找了{count}次")
break
elif l1[medain] > value:
count += 1
end = medain -1
else:
count += 1
beg = medain + 1
else:
print(f"{value}不在列表里面")
l1 = [1,2,3,4,5,6,7,8]
cc(l1,8)
# 法二:
def binary_search(sorted_array, val):
if not sorted_array:
return -1
beg = 0
end = len(sorted_array) - 1
while beg <= end:
mid = int((beg + end) / 2)
if sorted_array[mid] == val:
return mid
elif sorted_array[mid] > val:
end = mid - 1
else:
beg = mid + 1
return -1
a = list(range(10))
# # 正常值
print(binary_search(a, 1))
print(binary_search(a, -1))
#
# # 边界值
print(binary_search(a, 0))
二分查找
最新推荐文章于 2022-11-03 10:33:00 发布