纯算法实现
实现代码:
arr_list = [5, 7, 11, 22, 27, 33, 39, 52, 58]
middle = (left + right) // 2
count += 1
if seek_number > arr_list[middle]:
left = middle + 1
elif seek_number < arr_list[middle]:
right = middle - 1
else:
print('数字:%s找到了,索引值为:%s' % (seek_number, middle))
breakelse:
print("数字%s 没有找到" % seek_number)print("一共用了:%s次查找" % count)
运行结果:
递归法实现
在循环中定义了一个变量count,如果第一次循环后count没有变化,就说明输入的是有序序列,这时我们直接return退出循环,这时候的时间复杂度为O(n)
实现代码:
arr_list = [5, 7, 11, 22, 27, 33, 39, 52, 58]def binary_search(seek_number, left, right):
if left <= right:
middle = (left + right) // 2
if seek_number < arr_list[middle]:
right = middle - 1
elif seek_number > arr_list[middle]:
left = middle + 1
else:
return middle # 进行递归调用
return binary_search(seek_number, left, right)
# 当左侧索引大于右侧索引时,说明没有找到
else:
return -1# 查找的数字seek_number = 11# 列表左侧索引left = 0# 列表右侧索引right = len(arr_list) - 1print("查找的数字:%s,索引为:%s" % (seek_number, binary_search(seek_number, left, right)))
运行结果:
推荐学习:python视频教程
本文转载自:www.php.cn/python-tuto…
世间美好收藏家
粉丝