对于有序的列表(假设升序),我们可以估计目标项的大概位置。根据这一思路,我们能省去一些不必要的过程以达到快速搜索的目的。
过程:
1.找到列表的中间位置并与目的项进行比较。如果相等,则返回改位置
2.若不相等,假设目标项小于当前项,那么算法将搜索中间位置以前的部分,并重复上述操作(反之亦反)
def binarySearch(target, lyst):
"""Returns the position of the target item if found,
or -1 otherwise."""
left = 0
right = len(lyst) - 1
while left <= right:
midpoint = (left + right) // 2
if target == lyst[midpoint]:
return midpoint
elif target < lyst[midpoint]:
right = midpoint - 1
else:
left = midpoint + 1
return -1