import time
def binary_search(list,item):
# low和high用于每次查找的最大值和最小值
low = 0
high = len(list)-1
while low <= high:
# 每次取最大和最小值的中间值和所要查找值比较
mid = (high-low)//2
guess = list[mid+low]
# 如果guess等于要查找的值就返回位置
if guess == item:
return (mid+low)
# 如果guess大于要查找的值就把guess-1赋值给high。
if guess > item:
high = guess - 1
else:
low = guess + 1
return None
list = []
def main():
for i in range(100):
list.append(i)
t1 = time.time()
res = binary_search(list,69)
t2 = time.time()
print(res)
print(t2-t1)
if __name__ == '__main__':
main()
def binary_search(list,item):
# low和high用于每次查找的最大值和最小值
low = 0
high = len(list)-1
while low <= high:
# 每次取最大和最小值的中间值和所要查找值比较
mid = (high-low)//2
guess = list[mid+low]
# 如果guess等于要查找的值就返回位置
if guess == item:
return (mid+low)
# 如果guess大于要查找的值就把guess-1赋值给high。
if guess > item:
high = guess - 1
else:
low = guess + 1
return None
list = []
def main():
for i in range(100):
list.append(i)
t1 = time.time()
res = binary_search(list,69)
t2 = time.time()
print(res)
print(t2-t1)
if __name__ == '__main__':
main()