折半查找。
1 #include <iostream> 2 using namespace std; 3 #define N 10 4 int main() 5 { 6 int i,a[N]={-3,4,7,9,13,45,67,89,100,180},low=0,high=N-1,mid,k=-1,m; 7 cout<<"a数组中数据如下"<<endl; 8 for(int i=0;i<N;i++) 9 { 10 cout<<a[i]<<" "; 11 } 12 cout<<endl; 13 cin>>m; 14 while(low<=high) 15 { 16 mid=(low+high)/2; 17 if(m<a[mid]) 18 { 19 high=mid-1; 20 } 21 else 22 { 23 if(m>a[mid]) 24 low=mid+1; 25 else 26 { 27 k=mid; 28 break; 29 } 30 } 31 } 32 if(k>=0) 33 { 34 cout<<m<<","<<k<<endl; 35 } 36 else 37 { 38 cout<<"no found"<<endl; 39 } 40 41 }
标签:cout,int,编程,mid,C++,low,趣味 From: https://www.cnblogs.com/Lyh3012648079/p/17397803.html