| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | #include <stdio.h> #include <string.h> #define N 4 // 구조체 정의 struct student_info { char name[10]; int age; float weight; }; struct student_info students[N] = { {"홍길동", 504, 67.5}, {"이순신", 703, 80.3}, {"강감찬", 645, 77.0}, {"유관순", 205, 56.5} }; // 구조체 배열 출력 함수 void print_students(struct student_info arr[], int n) { for (int i = 0; i < n; i++) { printf("%-6s Age: %3d Weight: %5.1f\n", arr[i].name, arr[i].age, arr[i].weight); } printf("\n"); } // bubble sort: 이름 기준 void bubble_sort_name(struct student_info arr[], int n) { struct student_info tmp; for (int j = 0; j < n - 1; j++) { for (int i = 0; i < n - 1 - j; i++) { if (strcmp(arr[i].name, arr[i + 1].name) > 0) { tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; } } } } // bubble sort: 나이 기준 void bubble_sort_age(struct student_info arr[], int n) { struct student_info tmp; for (int j = 0; j < n - 1; j++) { for (int i = 0; i < n - 1 - j; i++) { if (arr[i].age > arr[i + 1].age) { tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; } } } } // bubble sort: 몸무게 기준 void bubble_sort_weight(struct student_info arr[], int n) { struct student_info tmp; for (int j = 0; j < n - 1; j++) { for (int i = 0; i < n - 1 - j; i++) { if (arr[i].weight > arr[i + 1].weight) { tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; } } } } int main() { struct student_info students2[N], students3[N]; memcpy(students2, students, sizeof(students)); memcpy(students3, students, sizeof(students)); // 이름으로 정렬 printf("이름순 정렬:\n"); bubble_sort_name(students, N); print_students(students, N); // 나이순 정렬 printf("나이순 정렬:\n"); bubble_sort_age(students2, N); print_students(students2, N); // 몸무게순 정렬 printf("몸무게순 정렬:\n"); bubble_sort_weight(students3, N); print_students(students3, N); return 0; } | cs |


struct_bubble_sort.png [50 KB]
struct_bubble_soft_dstruct.txt [3 KB]
자료구조 실습게시판