标签:否则 return == bin arch bsp middle 查找 返回
假定有n≥1个不同的整数已经按从小到大的顺序存放在数组元素a[0], … ,a[n-1]中。我们需要做的是判断整数x是否存放在某个数组元素中,如果是,即x=a[j],则返回j(被找到元素的下标);否则返回-1。
1 def BinarySearch(A,x): 2 n = len(A) 3 left, right = 0, n-1 4 while left <= right: 5 middle = (left+right+1)/2 6 if x == A[middle]: 7 return middle 8 elif x > A[middle]: 9 left = middle + 1 10 else: 11 right = middle - 1 12 return -1 # not found
递归算法:
1 # -*- coding: cp936 -*- 2 #返回x在A中的index 3 def BinarySearch(A,x,L,R): 4 n = len(A) 5 # L,R 分别为要查找的边界,可取0,n-1 6 left, right = L, R 7 while left <= right: 8 middle = (left + right +1)/2 9 if x == A[middle]: return middle 10 elif x > A[middle]: 11 return BinarySearch(A, x, middle + 1, right) 12 else: 13 return BinarySearch(A, x, left, middle - 1)
标签:否则 return == bin arch bsp middle 查找 返回
原文地址:http://www.cnblogs.com/immersion/p/7898963.html