首页 > 代码库 > 二分查找

二分查找

二分查找的一点思考

二分查找算法实现

#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;
}

另一种版本:

#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;
}

一点思考:

#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;
}