二分查找
二分查找是对一组有序序列进行查找。根据要查找的k和序列中间元素比较,动态的移动查找范围。以对折的方式缩小查找范围。
递归方式:
def binarySearch(A,left,right,k): if left<= right: mid =(left+right)//2 if A[mid] == k: return mid if A[mid]>k: return binarySearch(A,left,mid-1,k) #此处要返回函数运行结果而不是仅仅调用函数 else: return binarySearch(A,mid+1,right,k) else: return -1 A= [1,2,3,4,5,6,7] left = 0 right = len(A)-1 print(binarySearch(A,left,right,3))
非递归方式:
def binarySearch(A,k): left = 0 right =len(A)-1 while left<=right: mid = (right+left)//2 if A[mid] == k: return mid if A[mid]>k: right = mid-1 else: left = mid+1 return -1 a = [1,2,3,4,5] print(binarySearch(a,1))
时间: 2024-12-25 19:44:57