LearnFrenzy
Sign in Take a free test

Structures, Unions, Enums · Structure Programs · Question 5

Sort structures by marks, then by name, in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

Sort students by marks (highest first); students with equal marks go in alphabetical order.

Solution
main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct student {
    const char *name;
    int marks;
};

static int cmp(const void *a, const void *b) {
    const struct student *x = a, *y = b;
    if (x->marks != y->marks)
        return (y->marks > x->marks) - (y->marks < x->marks);   /* higher marks first */
    return strcmp(x->name, y->name);                            /* then A to Z */
}

int main(void) {
    struct student s[] = {{"Ravi", 82}, {"Asha", 91}, {"Meera", 82}, {"John", 75}, {"Dev", 91}};
    qsort(s, 5, sizeof s[0], cmp);
    for (int i = 0; i < 5; i++)
        printf("%-6s %d\n", s[i].name, s[i].marks);
    return 0;
}

Output Verified by compiling and running

Asha   91
Dev    91
Meera  82
Ravi   82
John   75

The comparator decides on the first key and falls back to the second only when the first is equal. qsort() is not stable, so the tie-break must be in the comparator.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links