Search code examples
c++sortingbubble-sort

Bubble Sort - Array of structs with an array of structs


How do I sort two array's of of structs(one of the arrays is a member of the other struct) with the same function using bubble sort (Descending order for students[] on Student::name and sort the classes[] array on Class::title?

struct Class
{
    string title; 
    int units;
    char grade;

};
struct Student
{
    string name;
    double gpa;
    Class classes[500];
};

In main:

Student students[SIZE];

I am attempting to sort an array of structs that each contain an array of structs that also need to be sorted using bubble sort. My sorting function is pasted below. It does not sort correctly rather it sorts the inner array of structs classes[] according to title correctly, and sorts the outer array st[] correctly on the first iteration of the for loop. Since on the second iteration the elements of st[] have been swapped the first element doesn't get sorted b/c currentStu is now set to the second element in the array.

void sort_name(Student st[], int numValues)
{
  int currentStu = 0;
  int currentClass = 0;

  for(currentStu = 0; currentStu < numValues; currentStu++)
  {
        for(currentClass = 0; st[currentStu].classes[currentClass].title != ""; currentClass++)
        {
            bubbleUpClass(st, currentClass, currentStu);
        }

        bubbleUpLastName(st, currentStu, numValues - 1);
  }
}

Solution

  • You don't really have a 2D array of students, which is (on the whole) a good thing. You need to apply two separate sorting processes, and they can be applied quite independently.

    1. You need to iterate through your list of students, sorting each of the lists of classes (one per student). It is not clear how you know how many classes a given student is taking, but that's a problem for you to solve. You can do this before or after (but not during) the other sort operation. It is readily parallelizable if that was of interest; you could divide the list of students up amongst N threads, giving each thread a suitable set of students to work on.

    2. You need to sort your overall list of students. This operation will affect the entire array of students (or, at least, the populated part of it). You will do this sort either before or after (but not during) the other sort operation.

    You will need two separate sort functions — or, if you borrow the design of the Standard C function qsort(), you will two separate comparator functions and a single sort algorithm.

    So, don't try to combine the two sort operations. Do them separately.