-3

I built a program in C++ that takes words from txt file and inputs into program. Program then stores these words into array. Now, I want to search a specific word among the array using binary search.

My txt file has the following words:

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

I can't find the words except Hello which is the first word. So please help me.

Rokas Višinskas
  • 533
  • 4
  • 12
mohinish
  • 21
  • 6
  • And when you used your debugger to run your program, one line at a time, and observe how your binary search function executes, one by line, inspect the values of all variables, as they change, and track your program logical's execution flow, what observations did you make? Do you know how to use a debugger? If not, this is an excellent opportunity for you to learn how to use it, so you can find and fix your own bugs without asking anyone else for help. Being able to use a debugger is a required skill for every C++ developer. No exceptions. This is exactly what a debugger is for. – Sam Varshavchik Oct 20 '19 at 13:26
  • You have `int res;` then `if (x == (words[m])) res = 0;` then `if (res == 0) return m;` Your `res` variable was used but not initialized when x is not equal to words[m]. So your program has Undefined Behavior. – drescherjm Oct 20 '19 at 13:26
  • 2
    Binary search algorithm expects its input to be sorted, but `words` is not. – Igor Tandetnik Oct 20 '19 at 13:28
  • @drescherjm Yes man! You are correct . It is behaving unusually because of that. You made my day!!! – mohinish Oct 20 '19 at 13:41
  • 1
    So, should I sort th words first save them in another array and then search? – mohinish Oct 20 '19 at 13:42
  • You could use a `std::set` and the binary search is built in. But you probably ought to use a `std::vector`, load the vector, sort the vector, then use `std::binary_search` (from the ``) to locate the element. – Eljay Oct 20 '19 at 14:06

1 Answers1

0

hopefully this work

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