fork(1) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. // Define a type to hold the score together with the name of the player
  5. typedef struct
  6. {
  7. char name[42];
  8. int score;
  9. } PlayerStats;
  10.  
  11. // Make a compare function to be used by qsort
  12. int cmpfunc (const void * a, const void * b){
  13. const PlayerStats* pA = a;
  14. const PlayerStats* pB = b;
  15. if (pA->score > pB->score) return -1;
  16. if (pA->score < pB->score) return 1;
  17. return 0;
  18. }
  19.  
  20. // A function for printing the players and their score
  21. void print_stats(PlayerStats *ps, int n)
  22. {
  23. for(int i=0; i<n; ++i) printf("%s : score=%d\n", ps[i].name, ps[i].score);
  24. }
  25.  
  26. int main(){
  27. // Make an array of players with scores.
  28. PlayerStats player_stats[3] = {{"p1", 17}, {"p2", 9}, {"p3", 42}};
  29. size_t numElements = sizeof player_stats / sizeof player_stats[0];
  30. size_t sizeElement = sizeof player_stats[0];
  31.  
  32. printf("Unsorted:\n");
  33. print_stats(player_stats, numElements);
  34.  
  35. // Use the standard qsort for sorting the array
  36. qsort(player_stats, numElements, sizeElement, cmpfunc);
  37.  
  38. printf("Sorted:\n");
  39. print_stats(player_stats, numElements);
  40.  
  41. return 0;
  42. }
  43.  
Success #stdin #stdout 0s 9424KB
stdin
Standard input is empty
stdout
Unsorted:
p1 : score=17
p2 : score=9
p3 : score=42
Sorted:
p3 : score=42
p1 : score=17
p2 : score=9