二分法查找

    二分法查找需要序列有序

#include<stdio.h>
#include<assert.h>
int binary_search(int *array,int n,int e) {
assert(array&&n>0);
int low=0,high=n-1,mid; while(low<=high) { mid=(low+high)/2; if(array[mid]==e) return mid; if(array[mid]>e) high=mid-1; else low=mid+1; } return -1; } int main() { int a[100]; int i; int e; for(i=0;i<100;i++) a[i]=i; scanf("%d",&e); int index=binary_search(a,100,e); if(-1==index) printf("Can not find %d\n",e); else printf("%d index=%d\n",e,index); getchar(); getchar(); return 0; }

 

posted @ 2015-11-22 19:47  _Bin  阅读(120)  评论(0编辑  收藏  举报