简单的二进制搜索对我不起作用。我正在尝试从文本文件中搜索单词

问题描述 投票:-2回答:1

我用C ++构建了一个程序,该程序将txt文件中的单词输入到程序中。然后程序将这些单词存储到数组中。现在,我想使用二进制搜索在数组中搜索特定单词。

我的txt文件包含以下单词:

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;
}

除了第一个单词你好以外,我找不到其他单词。所以请帮助我。

c++ search binary-search clion linear-search
1个回答
0
投票

希望这项工作

#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;
}
© www.soinside.com 2019 - 2024. All rights reserved.