二分法查找需要序列有序
#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 ",e); else printf("%d index=%d ",e,index); getchar(); getchar(); return 0; }