说明
二分法适用于查找有序数据
代码
# -*- coding: utf-8 -*-
def search_(array, num):
min = 0
max = len(array) - 1
count = 0
while min <= max:
count += 1
index = (min + max) // 2
print("这次的索引是:{},对比的是{}".format(index, array[index]))
if num > array[index]:
min = index + 1
elif num == array[index]:
print("找到了,一个找了{}次".format(count))
break
else:
max = index - 1
if __name__ == '__main__':
# 0 1 2 3 4 5 6 7 8 9 10 11
search_([1, 2, 3, 4, 5, 6, 77, 87, 91, 98, 99, 101], 99)
本文深入探讨了二分查找算法的实现原理,通过一个具体的Python代码示例,展示了如何在有序数组中高效查找目标数值。文章详细解释了算法的运行流程,包括初始化搜索范围、计算中间元素索引、比较目标值与中间元素以及调整搜索范围等关键步骤。
2659

被折叠的 条评论
为什么被折叠?



