Advertisement
STANAANDREY

sort studs

Feb 28th, 2023 (edited)
767
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.88 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #define LEN_MAX 31
  5.  
  6. typedef struct {
  7.   char name[LEN_MAX];
  8.   float grade;
  9. } Stud;
  10.  
  11. void readStud(Stud *stud) {
  12.   scanf("%30s%f", stud->name, &stud->grade);
  13. }
  14.  
  15. void printStud(const Stud *const stud) {
  16.   printf("%s %g\n", stud->name, stud->grade);
  17. }
  18.  
  19. int compStuds(const void *p1, const void *p2) {
  20.   const Stud stud1 = *(const Stud*)p1;
  21.   const Stud stud2 = *(const Stud*)p2;
  22.   if (stud1.grade == stud2.grade) {
  23.     return strcmp(stud1.name, stud2.name);
  24.   }
  25.   if (stud1.grade > stud2.grade) {
  26.     return -1;
  27.   }
  28.   return 1;
  29. }
  30.  
  31. int main() {
  32.   int n;
  33.   scanf("%d", &n);
  34.   Stud *arr = calloc(sizeof(Stud), n);
  35.   for (int i = 0; i < n; i++) {
  36.     readStud(arr + i);
  37.   }
  38.  
  39.   qsort(arr, n, sizeof(Stud), compStuds);
  40.   for (int i = 0; i < n; i++) {
  41.     printStud(arr + i);
  42.   }
  43.   free(arr);
  44.   return 0;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement