前提条件:数组排序
1 #include<iostream> 2 3 using namespace std; 4 5 int BinarySearch(int *a,const int x,const int n); 6 7 int main() 8 { 9 int x[]={1,2,3,4,5,6,7,8,9,10}; 10 int result; 11 int num=7;//要找的数
12 result=BinarySearch(x,num,10); 13 14 if(result<0) 15 cout<<”没找到!”<<endl; 16 else 17 cout<<"在m["<<result<<"]处找到"<<x[result]<<endl; 18 system("pause"); 19 return 0; 20 } 21 22 int BinarySearch(int *a,const int x,const int n) 23 { 24 int left,right,mid; 25 left=0;right=n-1; 26 27 while(left<=right) 28 { 29 mid=(left+right)/2; 30 if(a[mid] == x) 31 return mid; 32 else if(a[mid] < x) 33 left=mid+1; 34 else if(a[mid] > x) 35 right=mid-1; 36 } 37 return -1; 38 } 39
VS2010中运行结果: