二分查找

来源:互联网 发布:windows编程四大宝书 编辑:程序博客网 时间:2024/06/07 01:51

    二分查找算法适合于有序序列的查找:

    代码如下:

   

#include<stdio.h>int A[100000];int bsearch(int a[],int x,int y,int v);void main(){int n,v,flag;scanf("%d%d",&n,&v);for(int i=0;i<n;i++)scanf("%d",&A[i]);flag=bsearch(A,0,n,v);if(flag==-1)printf("Can't find: %d\n",v);elseprintf("%d is the %dth number\n",v,flag+1);}int bsearch(int a[],int x,int y,int v){int m;while(x<y){m=x+(y-x)/2;if(a[m]==v)return m;else if(a[m]<v)x=m+1;elsey=m;}return -1;}


    在有多个相同的数的时候,往往需要找到最靠前的那个位置:

   

int lower_bound(int *A,int x,int y,int v){int m;while(x<y){m=x+(y-x)/2;if(A[m]>=v)y=m;elsex=m+1;}return x;}


 最靠后的元素的下一个位置:

int upper_bound(int *A,int x,int y,int v){int m;while(x<y){m=x+(y-x)/2;if(A[m]<=v)x=m+1;elsey=m;}return y;}


 

原创粉丝点击