#include<iostream> #include<stdio.h> using namespace std; const int MAXN=1024; int bin_search(int a[], int len, int goal){//二分查找 int low,high,mid; low=0; high=len-1; while(low<=high){ mid=(high-low)/2+low;//直接使用(high+low)/2可能导致溢出 if(goal==a[mid]){ return mid; } else if(goal<a[mid]){//在左半边 high=mid-1; } else{//在右半边 low=mid+1; } } return -1;//没找到 } int main(){ int a[MAXN]; int i; int index; int goal; for (i=0;i<MAXN;++i){ a[i]=i; } goal=500; index=bin_search(a,MAXN,goal);//找goal这个数 if(index!=-1){ printf("%d's index:%d ",goal,index); } else{ printf("not found! "); } return 0; }