fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. // typedefと無名構造体を用いたBodyの定義
  5. typedef struct {
  6. int id;
  7. double height;
  8. } Body;
  9.  
  10. // 身長の昇順でソートするための比較関数
  11. int compareHeight(const void *a, const void *b) {
  12. Body *bodyA = (Body *)a;
  13. Body *bodyB = (Body *)b;
  14. if (bodyA->height < bodyB->height) return -1;
  15. else if (bodyA->height > bodyB->height) return 1;
  16. else return 0;
  17. }
  18.  
  19. int main() {
  20. // Body構造体の配列を宣言・初期化
  21. Body data[] = {
  22. {101, 172.5},
  23. {102, 165.3},
  24. {103, 180.2},
  25. {104, 158.9},
  26. {105, 170.0}
  27. };
  28.  
  29. int n = sizeof(data) / sizeof(data[0]);
  30.  
  31. // 身長の昇順にソート
  32. qsort(data, n, sizeof(Body), compareHeight);
  33.  
  34. // 結果を表示
  35. printf("ID\tHeight\n");
  36. for (int i = 0; i < n; i++) {
  37. printf("%d\t%.1f\n", data[i].id, data[i].height);
  38. }
  39.  
  40. return 0;
  41. }
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
ID	Height
104	158.9
102	165.3
105	170.0
101	172.5
103	180.2