'Sorting algorithm works the other way around, it also swaps equal members?

Task description:

Write a structure named patient that contains the name of a patient (up to 100 characters) in the name field and stores the patient's year of birth (a signed integer) in a field named birth_year. Write a sort function whose first parameter is an array that stores patient data, the second and its parameter is the size of this array (signed integer). The function set is ascending by year of birth sort the elements of the patient array. If two or more patients have the same year of birth, then the sort will keep the original order. (Of course, the items should still be in the correct order, only the order between patients of the same birth year should not change to the original compared to.)

My code is:

struct patient{
    char name[100];
    int birth_year;
};

void sort(struct patient patients[], int n) {

    struct patient temp;
    int i, j;

    for (i = 0; i < n - 1; i++)
    {
        for (j = 0; j < (n - 1-i); j++)
        {
            if (patients[j].birth_year < patients[j + 1].birth_year)
            {
                temp = patients[j];
                patients[j] = patients[j + 1];
                patients[j + 1] = temp;
            }
        }
    }

}

Unfortunately, I can't give the main function and only the first of the test cases, because a bot on a website always tests this snippet of code and the other data is secret.

The only problem is that I don’t figure out how to reverse the sorting. In addition, my function replaces members of equal age for some reason.

The first result MUST be:

A 1989

B 1995

C 1995

D 2001

E 2011

Instead of what I get:

E 2011

D 2001

B 1995

C 1995

A 1989



Solution 1:[1]

I don’t figure out how to reverse the sorting

When you swap, it's to push an item down the list. So if you want to place the items in ascending order, you want to swap when

patients[j].birth_year > patients[j + 1].birth_year

If two or more patients have the same year of birth, then the sort will keep the original order.

A sorting algorithm that preserves the order of equal items is called a stable sort. The algorithm you are using, bubble sort, is stable.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1