c++中的二进制搜索算法

问题描述 投票:0回答:1

我是编程新手,所以请帮我完成任务问题是:按y键后,while循环没有再运行.其次,如何打印或获取数组元素的降序?

谢谢!

#include <iostream>
using namespace std;

int main()
{
    int item;
    int flaging = 0;
    int ind_low = 0;
    int ind_high = 9;
    int ind_mid = (ind_low + ind_high) / 2;
    char conti;

    //Array declaration and taking user input
    int arr[10];

    cout << "enter some values here : \n" << endl;

    for (int i = 0; i < 10; i++)
    {
        cin >> arr[i];
    }

    // for sorthing the array
    int temp;
    for (int p = 1; p <= 9; p++)
        for (int c = 0; c <= 8; c++)
            if (arr[c] > arr[c + 1])
            {
                temp = arr[c];
                arr[c] = arr[c + 1];
                arr[c + 1] = temp;
            }

    do {
        //asking for searching

        cout << "Enter the value you want to search : " << endl;
        cin >> item;

        while (ind_low <= ind_high)
        {
            if (item == arr[ind_mid])
            {
                cout << "At " << ind_mid << " index the value " << item << " is found " << endl;
                flaging++;
                break;
            }

            if (item < arr[ind_mid])
            {
                ind_high = ind_mid - 1;
                ind_mid = (ind_low + ind_high) / 2;
            }
            else
            {
                ind_low = ind_mid + 1;
                ind_mid = (ind_low + ind_high) / 2;
            }
        }

        if (flaging == 0)
        {
            cout << "Value not found" << endl;
        }

        cout << "To search again press 'y', to exit press any key" << endl;
        cin >> conti;
    } while ((conti == 'y') || (conti == 'Y'));

}
c++ algorithm search binary
1个回答
0
投票

当我在我的PC上运行它时,按y后它又运行了,你能提供失败的输入吗? 对于第二个问题,你是什么意思?你可以做一个for循环,像这样。

for(int index = ARR_SIZE -1 ; index >= 0 ; --index){
cout << array[index];
}

编辑: 我明白你的意思. 每次运行后你应该重新设置你的索引,否则你会一直在同一个地方运行:

在你结束循环之前,你应该重新设置索引值

ind_low = 0;
ind_high = 9;
ind_mid = (ind_low + ind_high) / 2;

这样就可以从头到尾打印数组。

© www.soinside.com 2019 - 2024. All rights reserved.