I am having trouble writing a binary search code to search through my string array. I have the user enter the name of a search engine (engine) they want to locate and my binary search function searches through my string array. Here is my code...

//This function uses the binary search method to locate the search engine name in the array. The function
//returns either a -1 (search engine not found) or the number of the element (location) where it was found
int binSearch (string name[], string engine)
    int first = 0,
        last = MAX_NUM - 1,
        middle = 0;
        position = -1;
    bool found = false;
    while (!found && first <= last)
        middle = (first + last) / 2;
        if (name[middle] == engine)
            found = true;
            position = middle;
        else if (name[middle] > engine)
            last = middle - 1;
            first = middle + 1;
    return position;

Do any of your strings, including engine, have a trailing newline?

Add output statements at key points in the program to display important values. Like first, last, middle, string[middle].


Then post a complete test program so we're not forced to read your mind for necessary details.

This article has been dead for over six months. Start a new discussion instead.