首页 > 其他 > 详细

二分查找

时间:2014-05-13 21:53:05      阅读:291      评论:0      收藏:0      [点我收藏+]

二分查找的一点思考

二分查找算法实现

bubuko.com,布布扣
#define LOCAL
#include<cstdio>
#include<cstring>
#include<algorithm>
int const MAX_N=2<<10;
int const MAX_M=100;
int a[MAX_N],i,n,lb,ub,k;
void solve()
{
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    scanf("%d",&k);
    //排序 
    std::sort(a,a+n);
    //搜索 
    lb=-1;ub=n;
    while(ub-lb>1)
    {
        int mid=(ub+lb)/2;
        if(a[mid]>=k)
        {
            ub=mid;
        }else{
            lb=mid;
        }
    }
    for(i=0;i<n;i++)
    {
        printf("a[%d]=%d\t",i,a[i]);
    }    
    printf("\n%d\n",ub);
}
int main()
{
#ifdef LOCAL
    freopen("3.2.in","r",stdin);
    freopen("3.2.out","w",stdout);
#endif
    memset(a,0,sizeof(a));    
    while(~scanf("%d",&n))
    {
        solve();
    }
    return 0;
}
bubuko.com,布布扣

另一种版本:

bubuko.com,布布扣
#define LOCAL
#include<cstdio>
#include<cstring>
#include<algorithm>
int const MAX_N=2<<10;
int const MAX_M=100;
int a[MAX_N],i,n,lb,ub,k;
void solve()
{
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    scanf("%d",&k);
    //排序 
    std::sort(a,a+n);    
    lb=-1;ub=n;
    //搜索 
    for(i=0;i<MAX_M;i++)
    {
        int mid=(ub+lb)/2;
        if(a[mid]>=k)
        {
            ub=mid;
        }else{
            lb=mid;
        }
    }
    for(i=0;i<n;i++)
    {
        printf("%d ",a[i]);
    }    
    printf("\n%d\n",ub);
}
int main()
{
#ifdef LOCAL
    freopen("3.2.in","r",stdin);
    freopen("3.2.out","w",stdout);
#endif
    memset(a,0,sizeof(a));    
    while(~scanf("%d",&n))
    {
        solve();
    }
    return 0;
}
bubuko.com,布布扣

一点思考:

bubuko.com,布布扣
#define LOCAL
#include<cstdio>
#include<cstring>
#include<algorithm>
int const MAX_N=2<<10;
int const MAX_M=100;
void solve()
{    
    int i;
    //就是说1经过MAX_N次循环,能从1变到1267650600228229400000000000000.000000
    double first=1;
    for(i=0;i<MAX_M;i++)
    {
        first=first*2;
    }
    printf("%lf\n",first);
    //试想一根1267650600228229400000000000000.000000长的绳子,每次截半,100次之后就变成1了
    //由此对付一个足够的的数组,采用二分查找MAX_N次已经是绰绰有余了 
}
int main()
{
#ifdef LOCAL
    freopen("3.2.in","r",stdin);
    freopen("3.2.out","w",stdout);
#endif
    solve();
    return 0;
}
bubuko.com,布布扣

 

 

二分查找,布布扣,bubuko.com

二分查找

原文:http://www.cnblogs.com/jianfengyun/p/3724182.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!