# python之各种二分查找

array=[4,2,6,1,45,23,27,12,89,5]
# for key:find '==' value
def midfind(key):
length=len(array)
ans=length-1
l=0
r=length-1
while(l<=r):
mid=(l+r)>>1
if(array[mid]<key):
l=mid+1
elif(array[mid]>key):
r=mid-1
else:
return mid
return -1
# for key:find '>=key' min value
def midfind1(key):
length=len(array)
ans=-1
l=0
r=length-1
while(l<=r):
mid=(l+r)>>1
if(array[mid]<key):
ans=mid
l=mid+1
else: r=mid-1
return ans+1
#for key:find '<=key' max value
def midfind2(key):
length=len(array)
ans=length
l=0
r=length-1
while(l<=r):
mid=(l+r)>>1
if(array[mid]>key):
ans=mid
r=mid-1
else: l=mid+1
return ans-1
#for key:find > min value
def midfind3(key):
length=len(array)
ans=-1
l=0
r=length-1
while(l<=r):
mid=(l+r)>>1
if(array[mid]<=key):
ans=mid
l=mid+1
else: r=mid-1
return ans+1
#for key:find < max value
def midfind4(key):
length=len(array)
ans=length
l=0
r=length-1
while(l<=r):
mid=(l+r)>>1
if(array[mid]>=key):
ans=mid
r=mid-1
else: l=mid+1
return ans-1
array.sort()
print('after sort (key=24)')
print array

dex=midfind(24)
dex1=midfind1(24)
dex2=midfind2(24)
dex3=midfind3(24)
dex4=midfind4(24)
else: print array[dex]

print(array[dex1])
print(array[dex2])
print(array[dex3])
print(array[dex4])



>>>
after sort (key=24)
[1, 2, 4, 5, 6, 12, 23, 27, 45, 89]
27
23
27
23
>>> 

a=[3,6,9,12,15,20,23,35,47]
def midfind(key):
length=len(a)
l=0
r=length-1
while(l<r):
m=(l+r)>>1
#print ("%d %d %d"%(a[l],a[r],a[m]))
if(a[m]<key): l=m+1
else: r=m
return l-1
print midfind(22)
#print "*********"
print midfind(7)


while(l<r):
m=(l+r)>>1
#print ("%d %d %d"%(a[l],a[r],a[m]))
if(a[m]>key): r=m-1
else: l=m
return l-1