Program Doesn't Alphabetize Strings Help

I do not know what I am doing wrong. I cant seem to get my program to alphabetize a vector string. Can anyone help me spot the error? It displays the names, but not in a sorted order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
 




void sort_names(vector<string> &nameList)
{
     int i, minIndex;

     string minValue;

     int size;



     size = nameList.size();



     for (i = 0; i < (size - 1); i++)

     {

            minIndex = i;

            minValue = nameList[i];

     for (int index = i + 1; index < size; index++)

         {

              if (nameList[index] < minValue)

                 {

                 minValue = nameList[index];

                 minIndex = index;

                 }

          }

                nameList[minIndex] = nameList[i]; 
                 nameList[i] = minValue;

     }




      //cout << endl << "Sorted names..." << nameList[i] << endl;
Last edited on
It displays the names, but not in a sorted order.

Two things: Your display_names function does not display the names in the vector it is given as a parameter, and you don't call display_names after you call sort_names.

Get rid of lines 120 through 126. Change lines 129 to 138 to:
1
2
    for (int i=0; i<namelist.size(); ++i)
        cout << namelist[i] << '\n' ;


And remember to call display_names after you sort.
Last edited on

int i, minIndex;

string minValue;

int size;



size = nameList.size();



for (i = 0; i < (size - 1); i++)

{

minIndex = i;

minValue = nameList[i];

for (int index = i + 1; index < size; index++)

{

if (nameList[index] < minValue)

{

minValue = nameList[index];

minIndex = index;

}

}

nameList[minIndex] = nameList[i];
nameList[i] = minValue;

}




cout << endl << "These are the name that have been sorted...." << endl;
cout << endl;
cout << nameList[i] << endl;
}
Last edited on
What do you think cout << nameList[i] << endl; does in sort_names?
Thanks Cire!! Really appreciate your help!
Topic archived. No new replies allowed.