1 //数组a[]中有n各元素,已经按升序排序,待查找的元素x 2 sort(a,a+n); //升序排序 3 template<class Type> 4 int BinarySearch(Type a[],const Type&x,int n) 5 { 6 int left=0; //左边界 7 int right=n-1; //右边界 8 while(left<=right) 9 { 10 int middle=(left+right)/2; //中点 11 if(x==a[middle])return middle; //找到x,返回数组中的位置 12 if(x>a[middle]) left=middle+1; 13 else right=middle-1; 14 } 15 return -1; //未找到x 16 } 17 18 19 20 21 22 #include<iostream> 23 #include<algorithm> 24 using namespace std; 25 bool compare(int a,int b) 26 { 27 return a<b; //升序 28 } 29 template<class Type>int BinarySearch(Type a[],const Type&x,int n) 30 { 31 int left=0; 32 int right=n-1; 33 while(left<=right) 34 { 35 int middle=(left+right)/2; 36 if(a[middle]==x) return middle; 37 if(a[middle]<x) left=middle+1; 38 else right=middle-1; 39 } 40 return -1; 41 } 42 int main() 43 { 44 int a[20]; 45 int n,m; 46 cin>>n; 47 for(int i=0; i<n; i++) 48 { 49 cin>>a[i]; 50 } 51 sort(a,a+n,compare); 52 for(int i=0; i<n; i++) 53 { 54 cout<<a[i]<<" "; 55 } 56 cout<<endl; 57 m=BinarySearch(a,234,n); 58 cout<<m<<endl; 59 return 0; 60 }