算法 python
1.
# -*- coding:utf-8 -*-
import math
'''
二分查找(当列表是有序的)
'''
def binary_search(list, item):
low = 0
high = len(list) - 1
while low <= high:
mid = math.floor((low + high) / 2)
guess = list[mid]
if guess == item:
return mid
elif guess > item:
high = mid - 1
else:
low = mid + 1
return None
list = [1, 3, 6, 8, 9]
print(binary_search(list, 3))
print(binary_search(list, -1))
2.
浙公网安备 33010602011771号