我正在尝试制作一个二进制搜索程序,我的代码如下,但是当我给出偶数个元素时,它不会给出任何输出,而当我给出奇数个元素时,程序运行良好!程序先比较中间值,如果为假则比较小于或大于中间值
int main()
{
int n,a[50] ;
int i, j, temp,counter,searchv,f,l,mid;
cout<<"Enter no. of elements: ";
cin>>n;
f=0;
l=n-1;
mid=(f+l)/2;
cout<<"l= "<<l<<" mid= "<<mid<<"\n";
cout<<"Enter "<<n <<" values \n";
for(counter=0;counter<n;counter++)
{
cin>>a[counter];
}
for(j=0; j<n; j++)
{
for (int i=(n-1); i>j ;i--)
{
if (a[i]<a[i-1])
{
int temp=a[i-1];
a[i-1]=a[i];
a[i]=temp;
}
}
}
cout<<"SORTED ARRAY!!\n";
for(counter=f;counter<n;counter++)
{
cout<<"Value at Element "<<counter <<" is "<<a[counter];
cout<<endl;
}
cout<<"Enter number to search: ";
cin>>searchv;
if(a[mid]==searchv)
{
cout<<"searched value "<<searchv<<" founded at position "<<mid;
}
else if(searchv>a[mid])
{
for(counter=l;counter>mid;counter--)
{
if(a[counter]==searchv)
cout<<"searched value "<<searchv<<" founded at position "<<counter;
break;
}
}
else if(searchv<a[mid])
{
for(counter=0;counter<mid;counter++)
{
if(a[counter]==searchv)
cout<<"searched value "<<searchv<<" founded at position "<<counter;
break;
}
}
else
{
cout<<"Value not found\n";
}
getch();
return 0;
}
最佳答案
根据上面的回答,你可以加上这个
代替
if(a[mid]==searchv)
{
cout<<"searched value "<<searchv<<" founded at position "<<mid;
}
else if(searchv>a[mid])
{
for(counter=l;counter>mid;counter--)
{
if(a[counter]==searchv)
cout<<"searched value "<<searchv<<" founded at position "<<counter;
break;
}
}
else if(searchv<a[mid])
{
for(counter=0;counter<mid;counter++)
{
if(a[counter]==searchv)
cout<<"searched value "<<searchv<<" founded at position "<<counter;
break;
}
}
else
{
cout<<"Value not found\n";
}
你可以试试这个:
bool isFound = false;
for(counter=0;counter<l;counter++)
{
if(a[counter]==searchv)
{
cout<<"searched value "<<searchv<<" founded at position "<< counter << endl;
isFound = true;
}
}
if (isFound == false)
{
cout << "No result found." << endl;
}
关于c++ - 为什么当我放入偶数个元素时我的程序不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35860266/