fork download
  1. #include<stdio.h>
  2. #include<string.h>
  3. #define NUMBER 5
  4. #define NAME_LEN 64
  5.  
  6. typedef struct {
  7. char name[NAME_LEN];
  8. int height;
  9. float weight;
  10. long number;
  11. } Student;
  12.  
  13. void swap_Student(Student *x, Student *y) {
  14. Student temp = *x;
  15. *x = *y;
  16. *y = temp;
  17. }
  18.  
  19. void sort_by_name(Student a[], int n) {
  20. int i, j;
  21. for (i = 0; i < n-1; i++) {
  22. for (j = n-1; j > i; j--) {
  23. if (strcmp(a[j-1].name, a[j].name) > 0) {
  24. swap_Student(&a[j-1], &a[j]);
  25. }
  26. }
  27. }
  28. }
  29.  
  30. int main(void) {
  31. int i;
  32. Student std[] = {
  33. {"Sato", 178, 61.2, 21801609900L},
  34. {"Sanaka", 175, 62.5, 21801609911L},
  35. {"Takao", 173, 86.2, 21801609922L},
  36. {"Mike", 165, 72.3, 21801609933L},
  37. {"Masaki", 179, 77.5, 21801609944L},
  38. };
  39.  
  40. printf("ソート前:\n");
  41. for (i = 0; i < NUMBER; i++) {
  42. printf("%-8s %6d %6.1f %11ld\n", std[i].name, std[i].height, std[i].weight, std[i].number);
  43. }
  44.  
  45. sort_by_name(std, NUMBER);
  46.  
  47. puts("\n名前の辞書順にソートしました。");
  48. for (i = 0; i < NUMBER; i++) {
  49. printf("%-8s %6d %6.1f %11ld\n", std[i].name, std[i].height, std[i].weight, std[i].number);
  50. }
  51.  
  52. return 0;
  53. }
  54.  
Success #stdin #stdout 0s 5288KB
stdin
Standard input is empty
stdout
ソート前:
Sato        178   61.2 21801609900
Sanaka      175   62.5 21801609911
Takao       173   86.2 21801609922
Mike        165   72.3 21801609933
Masaki      179   77.5 21801609944

名前の辞書順にソートしました。
Masaki      179   77.5 21801609944
Mike        165   72.3 21801609933
Sanaka      175   62.5 21801609911
Sato        178   61.2 21801609900
Takao       173   86.2 21801609922