androidexpert35
androidexpert35

Reputation: 329

Generic way to sort a linked list with considering 3 parameters in C

i have simple linked list with this struct:

typedef struct exam {
    char name[100];
    int credits;
    int grade;
    struct exam* next;
} Exam;

I want to sort it in lexicographical way considering: The name sorted in alphabetic way, the credits and the grade sorted in a crescent way

Both credits and grade are positive and can assume any dsired number.

How would you do that?

Thank you!

Upvotes: 0

Views: 45

Answers (1)

dbush
dbush

Reputation: 223972

You need to compare each field in priority order and assign an ordering based on that. For example:

int cmp_examp(Exam *e1, Exam *e2)
{
    if (strcmp(e1->name, e2->name) < 0) {
        return -1;
    } else if (strcmp(e1->name, e2->name) > 0) {
        return 1;
    } else if (e1->credits < e2->credits) {
        return -1;
    } else if (e1->credits > e2->credits) {
        return 1;
    } else if (e1->grade < e2->grade) {
        return -1;
    } else if (e1->grade > e2->grade) {
        return 1;
    } else {
        return 0;
    }
}

This orders exams first by name, then by credits, then by grade.

Upvotes: 1

Related Questions