Простой бинарный поиск не работает для меня. Я пытаюсь найти слово из текстового файла - PullRequest
0 голосов
/ 20 октября 2019

Я создал программу на C ++, которая берет слова из текстового файла и вводит их в программу. Затем программа сохраняет эти слова в массиве. Теперь я хочу найти определенное слово в массиве с помощью двоичного поиска.

В моем текстовом файле есть следующие слова:

hello
world
hi
how
are
you
i
am
fine
thank
welcome
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>

using namespace std;

int binarySearch(string words[], const string& x,int n)
{
    int l = 0 ;
    int r = n - 1;
    while (l <= r)
    {
        int m = l + (r - l) / 2;

        int res;
        if (x == (words[m]))
            res = 0;

        // Check if x is present at mid
        if (res == 0)
            return m;

        // If x greater, ignore left half
        if (x > (words[m]))
            l = m + 1;

            // If x is smaller, ignore right half
        else
            r = m - 1;
    }

    return -1;
}

int main () {
    ifstream inFile;
    inFile.open("test.txt");

    if(inFile.fail()){
        cerr << "Error opening file"<< endl ;

        exit(1);
    }

    string x1;
    string words[100];
    int count=0,i=0;
    string str;

    while( !inFile.eof()) {
        inFile >> x1;
        words[i]=x1;
        count++;
        i++;
    }

    for (i=0;i<100;i++){
        cout<< words[i]<<endl;
    }

    string x;
    x = "how";
    int n = 14;
    int result = binarySearch(words , x,n);
    if (result == -1)
        cout << ("\nElement not present");
    else
        cout << ("Element found at index ") << result;

    return 0;
}

Я не могу найти слова, кромеПривет, который является первым словом. Поэтому, пожалуйста, помогите мне.

1 Ответ

0 голосов
/ 02 ноября 2019

надеюсь, эта работа

#include <iostream>
#include <fstream>
#include <string>
#include <cstring>

using namespace std;

int binarySearch(string words[], const string& x, int n)
{
    int l = 0;
    int r = n - 1;
    while (l <= r)
{
    int m = l + (r - l) / 2;

    int res = 0;
    if (x == (words[m]))
        res = 0;

    // Check if x is present at mid
    if (res == 0)
        return m;

    // If x greater, ignore left half
    if (x > (words[m]))
        l = m + 1;

    // If x is smaller, ignore right half
    else
        r = m - 1;
}

return -1;
}

int main() {
ifstream inFile;
inFile.open("test.txt");

if (inFile.fail()) {
    cerr << "Error opening file" << endl;

    exit(1);
}

string x1;
string words[100];
int count = 0, i = 0;
string str;

while (!inFile.eof()) {
    inFile >> x1;
    words[i] = x1;
    count++;
    i++;
}

for (i = 0; i < 100; i++) {
    cout << words[i] << endl;
}

string x;
x = "fine";
int n = 11;
int result = binarySearch(words, x, n);
if (result == -1)
    cout << ("\nElement not present");
else
    cout << ("Element found at index ") << result;

return 0;
}
...