// Un mismo arreglo, ordenado con qsort por tres criterios.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define COUNT 5

typedef struct {
    char name[20];
    int grade;
} Student;

int compare_by_name(const void *first, const void *second) {
    const Student *a = first;
    const Student *b = second;
    return strcmp(a->name, b->name);
}

int compare_by_grade_desc(const void *first, const void *second) {
    const Student *a = first;
    const Student *b = second;
    if (a->grade > b->grade) {
        return -1;
    }
    if (a->grade < b->grade) {
        return 1;
    }
    return 0;
}

int compare_by_grade_then_name(const void *first, const void *second) {
    int by_grade = compare_by_grade_desc(first, second);
    if (by_grade != 0) {
        return by_grade;
    }
    return compare_by_name(first, second);
}

void print_students(const char *title, const Student *students, int n) {
    printf("%s:\n", title);
    for (int i = 0; i < n; i++) {
        printf("  %-8s %2d\n", students[i].name, students[i].grade);
    }
}

int main(void) {
    Student students[COUNT] = {
        {"Rosa", 14}, {"Abel", 17}, {"Nadia", 14}, {"Luis", 9}, {"Carmen", 17},
    };

    qsort(students, COUNT, sizeof(students[0]), compare_by_name);
    print_students("por nombre", students, COUNT);

    qsort(students, COUNT, sizeof(students[0]), compare_by_grade_then_name);
    print_students("por nota y luego nombre", students, COUNT);
    return 0;
}
