二分查找算法
实现
def bi_search(nums, target):
low = 0
high = len(nums)-1
while low <= high:
mid = (low+high)//2
if target == nums[mid]:
return mid
elif target < nums[mid]:
high = mid-1
else:
low = mid+1
return None
测试
def test():
nums0 = [1,2,4,6,7,8,9,11,13,15,16,17,20,21,22,26,27,30]
assert bi_search(nums0, target=1) == 0
assert bi_search(nums0, target=6) == 3
assert bi_search(nums0, target=14)== None
print('All testcases pass!')
if __name__ == '__main__':
test()
结果:
$ python3 t.py
All testcases pass!