def liner_search(li, val):
for ind, v in enumerate(li):
if v == val:
return ind
else:
return None
def binary_search(li, val):
left = 0
right = len(li) - 1
while left <= right: # 候选区有值
mid = (left + right) // 2 # 整除
if li[mid] == val:
return mid
elif li[mid] > val: # 说明查找值在左侧
right = mid - 1
else: # 说明查找值在右侧时
left = mid + 1
return None
def binary_search2(low, hight, item, list): # python 递归版
if low > hight:
return -1
mid = low + (hight - low) // 2 # 计算mid值,注意是 hight-low
if list[mid] == item:
return mid
if list[mid] < item:
return binary_search2(mid + 1, hight, item, list)
if list[mid] > item:
return binary_search2(low, mid - 1, item, list)
li2 = list(range(100000000))
print(binary_search(li2, 50000000))
print(liner_search(li2, 50000000))
print(binary_search2(0, len(li2) - 1, 50000000, li2))