alist = [1, 2, 3, 4, 5, 6, 7, 8] def binarySearch(alist, target): first = 0 last = len(alist) - 1 while first <= last: middle_index = (first + last) // 2 if target > alist[middle_index]: first = middle_index + 1 elif target < alist[middle_index]: last = middle_index - 1 else: return middle_index return -1 ret=binarySearch(alist,5) print(ret)
该算法返回的是目标的索引值,也可以自行改变返回False或True。