from cal_time import get_running_time
@get_running_time
def bin_search(li, val):
"""
二分查找
:param li: 要查找的有序列表
:param val: 要查找的值
:return:
"""
n = len(li)
low = 0
high = n - 1
while low <= high:
mid = (low + high) // 2
if li[mid] == val:
return mid
elif li[mid] > val:
high = mid - 1
else:
low = mid + 1
return -1
def bin_search_rec(li, val, low, high):
"""
二分查找递归版
:param li: 要查找的列表
:param val: 要查找的值
:param low: 候选区域起始位置
:param high: 候选区域结束位置
:return:
"""
if low <= high:
mid = (low + high) // 2
if li[mid] == val:
return mid
elif li[mid] > val:
return bin_search_rec(li, val, low, mid-1)
else:
return bin_search_rec(li, val, mid+1, high)
return -1
@get_running_time
def b_search_r(li, val, low, high):
return bin_search_rec(li, val, low, high)