Home > Mobile >  Sort a list of members in ascending and descending order
Sort a list of members in ascending and descending order

Time:10-12

I'm creating a simple database containing students with the following information: first name, last name, personalnumber, study type (permanent or part time student).

If user hits "showasc" the program asks whether to show students in ascending order by their first name or last name.

Managed to sort the members by name, but the problem is that only the names gets sorted while the rest of the information about the student doesn't, it stays in the order it was created. Bare in mind that I'm still very new to programming.

This is the part of the code that sorts the names:

else if(strcmp(command, "showasc") == 0)  
{
    char input[15]; 
    printf("Show in ascendant order by first name or last name?\n ");
    scanf("%s", input);


    struct Student copyOfListOfStudents[20];
    memcpy(&copyOfListOfStudents, &listOfStudents, sizeof(listOfStudents));

    int i, j;
    char s[100];
    for(i=0;i<20;i  )
    {
        for(j=i 1;j<20;j  )
        {
            if(copyOfListOfStudents[i].valid  &&  copyOfListOfStudents[j].valid)
            {
                if(strcmp(copyOfListOfStudents[i].firstName,copyOfListOfStudents[j].firstName) > 0)
                {
                    strcpy(s,copyOfListOfStudents[i].firstName);
                    strcpy(copyOfListOfStudents[i].firstName,copyOfListOfStudents[j].firstName);
                    strcpy(copyOfListOfStudents[j].firstName,s);
                }
            }
            else
                break;
        }
    }
    printStudents(copyOfListOfStudents);

So for example, if user adds the the following students:

  • Lol Ipop, 7802034567, Full time
  • Anna Banana, 9901024356, Part time

And then wants to show students sorted by first name, this is what happens:

  • Anna Ipop, 7802034567, Full time
  • Lol Banana, 9901024356, Part time

How do I fix this problem? (I hope that the code I'm showing is sufficient!)

CodePudding user response:

You have already identified the problem. In your sorting algorithm, the names get sorted, but the other values are not.

To fix the issue, you need to change this part to swap the whole student struct:

if(strcmp(copyOfListOfStudents[i].firstName,copyOfListOfStudents[j].firstName) > 0)
{
    Student tmp;
    memcpy(tmp, copyOfListOfStudents[i], sizeof(Student));
    memcpy(copyOfListOfStudents[i], copyOfListOfStudents[j], sizeof(Student));
    memcpy(copyOfListOfStudents[j], tmp, sizeof(Student));
}

Code is untested...

  • Related