掌握折半查找算法的思想及程序实现。
代码:
#include <bits/stdc++.h>
using namespace std;
typedef struct BSearch{
int elem[20];
public:
void ini(){
for(int i=0;i<20;i++) elem[i]=rand()%91;
sort(elem,elem+20);
}
int Find(int x){
int l=0,r=19,mid;
while(l+1<=r){
mid=(l+r)/2;
if(elem[mid]<x){
l=mid+1;
}else
r=mid;
}
return l;
}
void show(){
for(int i=0;i<20;i++)
cout<<elem[i]<<' ';
cout<<endl;
}
}BSearch;
int main()
{
srand((unsigned long long)time(0));
BSearch a;
a.ini();
a.show();
int x,t;
while(cin>>x){
cout<<a.Find(x)<<endl;
}
}