很多时候,我们需要在一堆数字查找的不仅仅是目标值,还可能是比它大的,比它小的,大于等于它的,小于等于它的临近值。现在,老师正在验收作业,我无聊的等待。。。写写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=length-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-1 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=length-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-1 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) if(dex==-1): print('not found') 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] not found 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试想:对于上例的list,当下标l=4,r=5,如果a[m]<key仍然成立,l=m=4,这样会无限循环下去。(这都是整除过程floor向下取整惹的祸啊……)
相关例题:http://blog.csdn.net/thearcticocean/article/details/48632391