# BinarySearch 二分查找法_Python实现
# 二分查找法是对有序数组的查找.
def binary_search(li, num):
left = 0
right = len(li) - 1
while left <= right:
mid = (right + left)// 2
guess = li[mid]
if num < guess:
right = mid - 1
elif guess < num:
left = mid + 1
else:
return mid
return None
list = [1, 3, 35, 54, 55, 64, 65, 74, 165, 356, 645, 98984]
index = binary_search(list, 165)
print(index)
二分查找法是比较简单的查找方式.
对于有序数组来说, 一直询问该数值大于或者小于所需要
二分查找法, 唯一需要注意的是, 在比较了中间值mid之后.
所找值更大, 则查找范围左侧右移到mid下标+1
所找值更小, 则查找范围为右侧左移到mid下标-1