递归查找
def bi_search_re(num_list,val):
def bi_search(l, h):
if(l > h):
return -1
mid = (l + h) // 2
if(num_list[mid] == val):
return mid ;
if(num_list[mid] > val):
return bi_search(l, mid - 1)
else:
return bi_search(mid + 1, h)
return bi_search(0,len(num_list)-1)
num_list = [0,1,2,3,4]
print(bi_search_re(num_list,1))
print(bi_search_re(num_list,3))
二分法查找,前提:有序
def bi_search_iter(alist,item):
left, right = 0, len(alist) - 1
while(left <= right):
mid = left + (right - left) // 2 #(left + right) // 2 Java或c++容易溢出
if(item < mid):
right = mid -1
elif(item > mid):
left = mid + 1
else:
return mid
return -1
num_list = [0,1,2,3,4,5,6,7,8,9]
print(bi_search_iter(num_list,7))
print(bi_search_iter(num_list,4))
来源:CSDN
作者:huaxiangsiyi
链接:https://blog.csdn.net/huaxiangsiyi/article/details/104578116