簡體   English   中英

c++中的二分查找算法

[英]Binary search algorithm in c++

我是編程新手,所以請幫我完成任務,問題是:按 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'));

}

當我在按 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;

這將從頭到尾打印數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM