Search code examples
c++linear-search

Remove function not working properly


My remove function is acting up. Lets say if I add "Apple", "Boy", "Cat" into my array. It sorts it alphabetically. When I remove something, lets say "Boy", it removes it fine. But if I enter in "Brown" it removes "Cat" from my list. It will always remove the one below it alphabetically if it does not find it in the list. If I have those strings I stated above and I enter in "Dog", nothing happens because "Cat" is before "Dog". Any ideas?

void StringList::remove(string s)
{
    int loc = search(s, 0, numberOfStrings);
    if(loc!=-1)
    {
        for(int i=loc; i<(numberOfStrings)-1; i++)
        {
            str[i] = str[i+1];
        }
        numberOfStrings--;      
    }
}


int StringList::search(string s, int start, int end)
{
    for(int i=start; i<=end; i++)
    {
        if(str[i]>=s)
        {
            return i;
        }
    }
    return -1;
}

Solution

  • A couple of problems I see:

    In StringList::search, the line

    if (str[i] >= s)
    

    should be changed to

    if (str[i] == s)
    

    You want to find an exact match, not the first lexicographically "greater" string, correct?

    Next, the first line in StringList::remove should use

    numberOfStrings - 1
    

    instead of just

    numberOfStrings
    

    If numberOfStrings = 3, then you want to search in indices 0, 1, 2, not 0, 1, 2, 3.

    However, instead of changing the parameter in the first line, you could also change (in the function StringList::search) the line

    for (int i = start; i <= end; i++)
    

    to

    for (int i = start; i < end; i++)
    

    With these fixes, your algorithm should work.

    The reason you would try to remove "Brown" and get "Cat" removed is because of the lexicographic "greater than" operation in the searching method. When you gave it "Brown", it would see "Cat" and say, hey! "Cat" > "Brown"! Let's return the index of "Cat"! And then the remove method would, well, remove "Cat"...