c++ - 为什么当我放入偶数个元素时我的程序不工作

标签 c++ c arrays binary-search

我正在尝试制作一个二进制搜索程序,我的代码如下,但是当我给出偶数个元素时,它不会给出任何输出,而当我给出奇数个元素时,程序运行良好!程序先比较中间值,如果为假则比较小于或大于中间值

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/

相关文章:

c++ - curlpp 链接错误

c++ - 如何直接操作终端输出缓冲区

c - 为什么 openmp 不并行化这段代码?

c - 以最有效的方式读取 CGI POST 数据

python - 比较两个 mask 以确定哪个 mask 比另一个 mask 更矩形->测量矩形

c++ - 2个类,都有指针。需要它们要么指向自己的类型,要么指向对方的类型

C++ - 从整数数组中插入和提取字符

c - 将文件中的单词存储到 C 中的数组中

php - 重新排列 php 关联数组

java - 有 Intent 地在 2 个 Activity 之间传递数组