fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #define SIZE 6
  5. #define MAX 3
  6.  
  7. int scorecmp(const void *a, const void *b);
  8. int ComparePlayerScore( const void* ap , const void* bp );
  9. int CompareInt( const int a , const int b );
  10.  
  11. typedef struct {
  12. double score;
  13. int player_num;
  14. } player_t;
  15.  
  16. struct top3_players {
  17. player_t *top[3];
  18. };
  19.  
  20. void top3_determine(struct top3_players *top, player_t *players, size_t n) {
  21. player_t *top1 = NULL;
  22. player_t *top2 = NULL;
  23. player_t *top3 = NULL;
  24. for (size_t i = 0; i < n; i++) {
  25. player_t *player = &players[i];
  26. if (top1 == NULL || ComparePlayerScore(player, top1) < 0) {
  27. top3 = top2;
  28. top2 = top1;
  29. top1 = player;
  30. } else if (top2 == NULL || ComparePlayerScore(player, top2) < 0) {
  31. top3 = top2;
  32. top2 = player;
  33. } else if (top3 == NULL || ComparePlayerScore(player, top3) < 0) {
  34. top3 = player;
  35. }
  36. }
  37. top->top[0] = top1;
  38. top->top[1] = top2;
  39. top->top[2] = top3;
  40. }
  41.  
  42. int
  43. main(int argc, char *argv[]) {
  44. int i;
  45.  
  46. int player_numbers[] = {1, 2, 3, 4, 5, 6};
  47. double scores[] = {0.765, 0.454, 0.454, 0.345, 0.643, 0.532};
  48.  
  49. player_t *players = malloc(SIZE * sizeof(player_t));
  50.  
  51. for (i = 0; i < SIZE; i++) {
  52. players[i].score = scores[i];
  53. players[i].player_num = player_numbers[i];
  54. }
  55.  
  56. struct top3_players top;
  57. top3_determine(&top, players, SIZE);
  58.  
  59. for (i = 0; i < MAX; i++) {
  60. printf("Player %d: Score: %.3f\n", top.top[i]->player_num, top.top[i]->score);
  61. }
  62.  
  63. free(players);
  64.  
  65. return 0;
  66. }
  67.  
  68. int ComparePlayerScore( const void* ap , const void* bp ) {
  69. const player_t* const a = ap;
  70. const player_t* const b = bp;
  71.  
  72. if( a->score == b->score ){
  73. return CompareInt( a->player_num , b->player_num );
  74. }
  75. else if( a->score > b->score ) {
  76. return -1;
  77. }
  78. else {
  79. return 1;
  80. }
  81. }
  82.  
  83. int CompareInt( const int a , const int b ) {
  84. if( a < b ){
  85. return -1;
  86. }
  87. else if( a > b ){
  88. return 1;
  89. }
  90.  
  91. return 0;
  92. }
  93.  
Success #stdin #stdout 0s 2300KB
stdin
Standard input is empty
stdout
Player 1: Score: 0.765
Player 5: Score: 0.643
Player 6: Score: 0.532