0

I am trying to find a user input word inside a string vector using binary search. But it always returns a positive integer. The vector is sorted and read from a txt file. The file looks like.

aah
aal
aas

and so on.

    int binarySearchString(vector<string> arr, string x, int n) {
    int lower = 0;
    int upper = n - 1;
    while (lower <= upper) {
    int mid = lower + (upper - lower) / 2;
    int res;
    if (x == (arr[mid]))
     res = 0;
    if (res == 0)
     return mid;
    if (x > (arr[mid]))
      lower = mid + 1;
    else
     upper = mid - 1;
    }
    return -1;
    }
  • 1
    You might want to initialize the variable `res`. Right now, it becomes either 0 after an if, or undefined (actually, any value, 0 or non-0) otherwise. – Gassa Mar 03 '22 at 00:16
  • 2
    After fixing that, you never mentioned it, but its important. Your vector is sorted, *right* ? binary search won't work if it isn't. Also, I see zero reason to pass that vector by-value; you'd be better off with `vector const& arr`. Finally, if this isn't for some odd academic exercise, `std::lower_bound` will get you most of the way there with far lass effort. – WhozCraig Mar 03 '22 at 00:22

1 Answers1

0

As it is, unless x == (arr[mid]) is true, this code should throw a runtime exception because res will be used in the next if statement before it's been initialized. When I initialize res to some negative value, the function seems to work.

int binarySearchString(vector<string> arr, string x, int n) {
    int lower = 0;
    int upper = n - 1;
    while (lower <= upper) {
        int mid = lower + (upper - lower) / 2;
        int res = -2;

        if (x == (arr[mid]))
            res = 0;

        if (res == 0)
            return mid;

        if (x > (arr[mid]))
            lower = mid + 1;
        else
            upper = mid - 1;
    }
    return -1;
}

Calling it with binarySearchString(words, "bbb", 3); returns -1.

int main()
{
    vector<string> words;
    words.push_back("aah");
    words.push_back("aal");
    words.push_back("aas");

    int retVal = binarySearchString(words, "bbb", 3);

    std::cout << "Returned: " << retVal << std::endl;

    system("pause");
    return 0;
}
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880