【发布时间】:2018-02-01 22:06:56
【问题描述】:
关于列表中点的计算:为什么会有
i = (first +last) //2
并且last 被初始化为len(a_list) - 1?根据我的快速测试,这个算法没有 -1 可以正常工作。
def binary_search(a_list, item):
"""Performs iterative binary search to find the position of an integer in a given, sorted, list.
a_list -- sorted list of integers
item -- integer you are searching for the position of
"""
first = 0
last = len(a_list) - 1
while first <= last:
i = (first + last) / 2
if a_list[i] == item:
return '{item} found at position {i}'.format(item=item, i=i)
elif a_list[i] > item:
last = i - 1
elif a_list[i] < item:
first = i + 1
else:
return '{item} not found in the list'.format(item=item)
【问题讨论】: