fork download
  1. #include <stdio.h>
  2.  
  3. // 構造体Bodyの定義
  4. struct Body {
  5. int id;
  6. int weight;
  7. int height;
  8. };
  9.  
  10. // 構造体を入れ替えるためのswap関数
  11. void swap(struct Body *x, struct Body *y) {
  12. struct Body temp = *x;
  13. *x = *y;
  14. *y = temp;
  15. }
  16.  
  17. int main() {
  18. // 構造体配列の初期化
  19. struct Body a[] = {
  20. {1, 65, 170},
  21. {2, 60, 160},
  22. {3, 70, 180},
  23. {4, 55, 155},
  24. {5, 80, 175}
  25. };
  26. int n = sizeof(a) / sizeof(a[0]); // 配列の要素数
  27.  
  28. // 身長の逆順(降順)にバブルソート
  29. for (int i = 0; i < n - 1; i++) {
  30. for (int j = 0; j < n - 1 - i; j++) {
  31. if (a[j].height < a[j + 1].height) { // 逆順なので「<」で比較
  32. swap(&a[j], &a[j + 1]);
  33. }
  34. }
  35. }
  36.  
  37. // 結果の表示
  38. printf("ID\t体重\t身長\n");
  39. for (int i = 0; i < n; i++) {
  40. printf("%d\t%d\t%d\n", a[i].id, a[i].weight, a[i].height);
  41. }
  42.  
  43. return 0;
  44. }
Success #stdin #stdout 0s 5332KB
stdin
Standard input is empty
stdout
ID	体重	身長
3	70	180
5	80	175
1	65	170
2	60	160
4	55	155