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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!