python3 二分查找法实现
code
def binarySearch(alist, item): first = 0 last = len(alist) - 1 while first <= last: mid = (first + last)//2 if alist[mid] > item: last = mid - 1 elif alist[mid] < item: first = mid + 1 else: return mid+1 return -1 test = [0, 1, 2, 8, 13, 17, 19, 32, 42] print("位置->",binarySearch(test, 8))
outputs
macname@MacdeMBP ~ % python3 test.py 位置-> 4 macname@MacdeMBP ~ %