2

For some reason I cannot get this sort the names correctly. Can anyone tell me what is wrong with it? As far as I can tell the problem is that the strings are not compared correctly. I have tried string comparisons before, and I know this kind of code should work. It really has me stumped.

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

void sortNames(vector<string> &);

void main()
{
    vector<string> namesList;
    ifstream namesFile;
    namesFile.open("Names.txt");

    // Make sure the file exists.
    if (namesFile)
    {
        // Get the names from the file.
        string name;
        while (getline(namesFile, name))
            namesList.push_back(name);

        // Sort the imported names.
        sortNames(namesList);

        for (int i = 0; i < namesList.size(); i++)
            cout << namesList[i] << endl;
    }
    else
    {
        cout << "Data files are missing";
    }

    namesFile.close();
}

void sortNames(vector<string> &list)
{
    for (int i = 0; i < list.size(); i++)
    {
        // Find the lowest value after i.
        int lowIndex = i;
        for (int j = i + 1; j < list.size(); j++)
        {
            string name = list[i];
            string name2 = list[j];

            if (name > name2)
                lowIndex = j;
        }

        // Flip the elements if there was a value lower than i.
        if (i != lowIndex)
        {
            string temp = list[i];
            list[i] = list[lowIndex];
            list[lowIndex] = temp;
        }
    }
}
2
  • 7
    You do know you can sort a vector using std::sort? Commented Mar 8, 2013 at 22:51
  • 2
    This is a learning exercise in a textbook to learn sorting and searching algorithms. Commented Mar 8, 2013 at 22:54

2 Answers 2

5

Here is the problem: this line

string name = list[i];

should be

string name = list[lowIndex];

Your current implementation compares the element at j not to the smallest string that you have found so far, but to the string at index i. That is incorrect, because it does not find the smallest remaining string: instead, it finds the last string in the vector that is smaller than the current element at index i, which is not what you want.

Sign up to request clarification or add additional context in comments.

Comments

0

rather than string name = list[i];, you want string name = list[lowIndex];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.