作者在 2011-12-17 22:14:01 发布以下内容
#include<iostream>
using namespace std;
int BinarySeach(int a[],int& x,int n)
{
int left=0;
int right=n-1;
while(left<=right)
{
int middle=(left+right)/2;
if(x==a[middle])return middle;
if(x>a[middle])left=middle+1;
else right=middle-1;
}
return -1;
}
int main()
{
cout<<"请输入数字个数,小于50个:"<<endl;
int n;
while(cin>>n)
{
int a[50],i;
cout<<"请输入"<<n<<"个数"<<endl;
for(i=0;i<n;i++)
{
cin>>a[i];
}
cout<<"请输入查找数:"<<endl;
int x;
cin>>x;
int t;
t=BinarySeach(a,x,n);
if(t==-1)
cout<<"没有值为"<<x<<"的数"<<endl;
else
cout<<"值为"<<x<<"的数下标为"<<t<<endl;
}
return 0;
}
using namespace std;
int BinarySeach(int a[],int& x,int n)
{
int left=0;
int right=n-1;
while(left<=right)
{
int middle=(left+right)/2;
if(x==a[middle])return middle;
if(x>a[middle])left=middle+1;
else right=middle-1;
}
return -1;
}
int main()
{
cout<<"请输入数字个数,小于50个:"<<endl;
int n;
while(cin>>n)
{
int a[50],i;
cout<<"请输入"<<n<<"个数"<<endl;
for(i=0;i<n;i++)
{
cin>>a[i];
}
cout<<"请输入查找数:"<<endl;
int x;
cin>>x;
int t;
t=BinarySeach(a,x,n);
if(t==-1)
cout<<"没有值为"<<x<<"的数"<<endl;
else
cout<<"值为"<<x<<"的数下标为"<<t<<endl;
}
return 0;
}