递归和非递归形式实现二分查找
#coding:utf-8
a=[1, 2, 3, 4, 5, 6, 8, 20, 24, 31, 35]
#-----------------递归二分查找------------------
b=10
def binarySearch(array,n,left,right):
mid=left+(right-left)/2
if(left>right):
print 'find failed'
return -1
else:
if(array[mid]>n):
return binarySearch(array, n, left, mid-1)
elif(array[mid]<n):
return binarySearch(array, n, mid+1, right)
else:
print 'find it'
return mid
print binarySearch(a, b, 0, len(a)-1)
#-------------------非递归查找------------------------
c=5
def binary_Search(a,n):
low = 0
high = len(a)-1
while low <= high:
middle = (low+high)/2
if a[middle] == n:
print 'find it'
return middle+1
elif a[middle] < n:
low = middle + 1
else:
high = middle - 1
print 'find failed'
return -1
print binary_Search(a,c)