码迷,mamicode.com
首页 > 其他好文 > 详细

二分的姿势=_=

时间:2014-12-03 00:34:03      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   sp   strong   on   2014   log   as   

二分查找:


1:大于等于xx的第一个数

int bin_s(int xx)
{
        int l=1,r=10;
        int ans=-1;
        while(l<=r){
                int m=(l+r)>>1;
                if(a[m]>=xx) ans=m,r=m-1;  //!!!
                else l=m+1;
        }
        return ans;
}
e.g:  int a[]={0,1,2,5,5,5,5,7,8,9,10};
in:           5
out:        3
2:大于xx的第一个数
int bin_s(int xx)
{
        int l=1,r=10;
        int ans=-1;
        while(l<=r){
                int m=(l+r)>>1;
                if(a[m]>xx) ans=m,r=m-1;  //!!!
                else l=m+1;
        }
        return ans;
}
e.g:  int a[]={0,1,2,5,5,5,5,7,8,9,10};
<pre name="code" class="cpp">in:           5
out:        7


3:小于等于xx的第一个数(接近xx)
int bin_s(int xx)
{
        int l=1,r=10;
        int ans=-1;
        while(l<=r){
                int m=(l+r)>>1;
                if(a[m]>xx) r=m-1;
                else ans=m,l=m+1;
        }
        return ans;
}

e.g:  int a[]={0,1,2,5,5,5,5,7,8,9,10};
<pre name="code" class="cpp">in:           5
out:        6

4:小于xx的第一个数(接近xx)
int bin_s(int xx)
{
        int l=1,r=10;
        int ans=-1;
        while(l<=r){
                int m=(l+r)>>1;
                if(a[m]>=xx) r=m-1;
                else ans=m,l=m+1;
        }
        return ans;
}
e.g:  int a[]={0,1,2,5,5,5,5,7,8,9,10};
<pre name="code" class="cpp">in:           5
out:        2




二分的姿势=_=

标签:style   blog   color   sp   strong   on   2014   log   as   

原文地址:http://blog.csdn.net/code_or_code/article/details/41686031

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!