二分法查找
二分查找--非递归算法 # lst = [22,33,44,55,66,77,88,99,101,238,345,456,567,678,789] # n=238 # left = 0 # right = len(lst)-1 # count = 1 # while left<=right: # middle = (left+right)//2 # if n <lst[middle]: # right = middle-1 # elif n > lst[middle]: # left = middle+1 # else: # print(count) # print(middle) # break # count = count + 1 # else: # print("不存在")
普通递归二分法查找 def binary_search(n,left,right): if left<=right: middle = (left+right)//2 if n < lst[middle]: right = middle -1 elif n > lst[middle]: left= middle+1 else: return middle return binary_search(n,left,right) else: return -1 print(binary_search(567,0,len(lst)-1))
#递归 二分法,很难计算位置 # def binary_search(ls,target): # left = 0 # right = len(ls) - 1 # if left > right: # print("不在这里") # middle = (left+right)//2 # if target< ls[middle]: # return binary_search(ls[:middle],target) # elif target > ls[middle]: # return binary_search(ls[middle+1:],target) # else: # print("在这里")
#递归二分法2
def search(l,aim,start=0,end=None): if end is None:end = len(l)-1 if start<=end: mid = start + (end-start)//2 mid_value = l[mid] if aim > mid_value: start = mid+1 ret = search(l,aim,start,end) return ret elif aim < mid_value: end = mid-1 ret = search(l,aim,start,end) return ret else: return mid else: pass