2分查找的注意事项: 1.数组必须是排好序 2.如果数组中有两个以上的相同数据,则查找不准备 #include <iostream> using namespace std; //声明一个2分查找函数 //返回值:如果数组中有个数就返回他的下标,如果没有这个数就返回数组长度 //参数(要查找的数,在那个数组中查找,数组大小) int find(int,int [],int total); int main() { int a[]={12,34,56,78,82,99,101,455,999}; //求出数组长度 int total=sizeof(a)/sizeof(int); int check=find(99,a,total); if(check==total) cout<<"没有找到数据。"<<endl; else cout<<"要查找的数据在数组中的位置是:"<<check<<endl;//下标从0开始 return 0; } int find(int m,int a[],int total) { int start=0,end=total-1,i; while (start<=end) { i=(start+end)/2;//先查找数组中间的下标 if(m==a[i]) return i;//找到数了就返回他的下标 if(m>a[i]) start=i+1; else end=i-1; } //没有找到这个数就返回数组长度 return total; }