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;
        else 
            first = middle + 1;
    }
    return position;
}

Is your array sorted?

Is your array sorted?

yes

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].

yes

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.