简体   繁体   English

c++中的二分查找算法

[英]Binary search algorithm in c++

I am new to programming so please help me completing the task the problem is: After pressing y the while loop does not run again.我是编程新手,所以请帮我完成任务,问题是:按 y 后,while 循环不再运行。 and secondly, how to print or get the array elements in descending order?其次,如何按降序打印或获取数组元素?

thank you!谢谢你!

#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'));

}

when I ran it on my pc after pressing y it did run again, can you provide the input that failed you?当我在按 y 后在我的电脑上运行它时,它确实再次运行了,你能提供让你失败的输入吗? for the second question what do you mean?对于第二个问题,你是什么意思? you can do a for loop that goes like this:你可以做一个这样的for循环:

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

edit: I understand what you mean.编辑:我明白你的意思。 after each run you should reset your indexes otherwise you will always run on the same once:每次运行后,您应该重置索引,否则您将始终运行一次:

before you end the loop the values should be reseted.在结束循环之前,应重置值。

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

that gonna print the array from end to start.这将从头到尾打印数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM