Sorting name in alpha order

Hi

I am having troubles sorting names in alpha order for these names:
John DOE, jane Doe, WODAN YMIR. after the sorting it would output as: jane Doe, WODAN YMIR, John DOE, which is not in correct order.

here is my code:

#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
#include <cctype>

// for conversion to lower case lettering
class toLower {public: char operator() (char c) const {return tolower(c);}};

int main()
{
const int MAX_NAMES = 8; // capacity
int nNames = 0; // initially empty
string name[MAX_NAMES];
string lowerName[MAX_NAMES];



for (i = 0; i < nNames; i++)
{
lowerName[i] = name[i];
}


for (i = 0; i < nNames; i++)
{
transform(lowerName[i].begin(), lowerName[i].end(), lowerName[i].begin(), toLower());
}

string temp;

// sort the students' names alphabetically
for (i = 0; i < nNames; i++)
{
for (int j = i + 1; j < nNames; j++)
{
if (lowerName[i] > lowerName[j])
{
temp = name[i];

name[i] = name[j];
name[j] = temp;
}
}
}

for (i = 0; i < nNames; i++)
{
cout << name[i] << endl;
}

fin.close ();

} // main
Last edited on
In your sorting loop, you're comparing the values of "lowerName" but swapping only the values of "name".
You need to swap the values in both arrays
Thanks. That worked perfectly.
Although I still don't understand why I need to also swap the temporary array (lowerName) because it is not suppose to be output them to the screen. Only the one with the original case
What you are sorting are the lower case names, so that's the lower case names that should be swapped.
Topic archived. No new replies allowed.