Selection sort in alphabetical order not sorting

Hello, I am working on an assignment where we need to sort a list of names and corresponding grades into alphabetical order, but my code is not sorting. The inputs are in the format of John Smith with a space in the middle. I might make another topic for it but if someone can also answer how to sort by last name when it is in a single string that would be great to. Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  void SortByFirstName(vector<string> &students, vector<double> &grades){
   cout << "Sorting by first name" << endl;
   
   int i;
   int j;
   string temp;
   int indexSmallest;
   
 for (i = 0; i < students.size() - 1; ++i){
    indexSmallest = i;
    
    for (j = i + 1; i < students.size(); ++ j){
       
       if (students[j] < students[indexSmallest]){
          indexSmallest = j;
       }
    }
    if (indexSmallest != i){
    temp = students[i];
    students[i] = students[indexSmallest];
    students[indexSmallest] = temp;
      }
   }
Look really close at line 12 above.
Sorry dutch, I don't see it. Sorry, I'm pretty new.
Last edited on
The index variable of the inner loop is j, but you are using i for the comparison.

1
2
3
4
5
6
7
8
9
10
11
12
void SortByFirstName(vector<string>& students, vector<double>& grades) {
    for (int i = 0; i < int(students.size()) - 1; ++i) {
        int min = i;
        for (int j = i + 1; j < int(students.size()); ++ j)
            if (students[j] < students[min])
                min = j;
        if (min != i) {
            swap(students[i], students[min]);
            swap(grades[i], grades[min]);
        }
    }
}

The int casts on .size() serve two purposes: they silence a compiler warning, and it fixes a bug that your code would've had if passed a zero-length vector. size() returns an unsigned value. An unsigned 0 minus 1 yields the maximum unsigned value, which would certainly blow your code up.
Thank you, that worked!
Topic archived. No new replies allowed.