이 문제에서는 student_id, student_name, student_percentage가 포함된 학생 레코드가 제공됩니다. 우리의 임무는 학생 기록을 구조로 저장하고 이름별로 정렬하는 C 프로그램을 만드는 것입니다.
문제를 이해하기 위해 예를 들어보겠습니다.
입력 - 학생 기록 =
{{ student_id = 1, student_name = nupur, student_percentage = 98}, { student_id = 2, student_name = Akash, student_percentage = 75}, { student_id = 3, student_name = Yash, student_percentage = 62}, { student_id = 4, student_name = Jyoti, student_percentage = 87}, { student_id = 5, student_name = Ramlal, student_percentage = 80}}
출력 - 학생 기록 =
{{ student_id = 2, student_name = Akash, student_percentage = 75}, { student_id = 4, student_name = Jyoti, student_percentage = 87}, { student_id = 1, student_name = nupur, student_percentage = 98}, { student_id = 5, student_name = Ramlal, student_percentage = 80}, { student_id = 3, student_name = Yash, student_percentage = 62}}
이 문제를 해결하기 위해 먼저 학생의 세부 정보를 저장할 구조를 만듭니다. 이제 qsort()를 사용하고 해당 qsort에서 strcmp() 메서드를 사용하여 구조의 이름을 비교하는 이 qsort에 대한 비교기 함수를 정의합니다.
예시
학생 기록을 구조로 저장하고 이름별로 정렬하는 프로그램
//C program to store Student records as Structures and Sort them by Name #include <stdio.h> #include <stdlib.h> #include <string.h> struct Student { int student_id; char* student_name; int student_percentage; }; int comparator(const void* s1, const void* s2){ return strcmp(((struct Student*)s1)->student_name,((struct Student*)s2)->student_name); } int main() { int n = 5; struct Student arr[n]; //student 1 arr[0].student_id = 1; arr[0].student_name = "Nupur"; arr[0].student_percentage = 98; //student 2 arr[1].student_id = 2; arr[1].student_name = "Akash"; arr[1].student_percentage = 75; //student 3 arr[2].student_id = 3; arr[2].student_name = "Yash"; arr[2].student_percentage = 62; //student 4 arr[3].student_id = 4; arr[3].student_name = "Jyoti"; arr[3].student_percentage = 87; //student 5 arr[4].student_id = 5; arr[4].student_name = "Ramlal"; arr[4].student_percentage = 80; printf("Unsorted Student Record:\n"); for (int i = 0; i < n; i++) { printf("Id = %d, Name = %s, Age = %d \n", arr[i].student_id, arr[i].student_name, arr[i].student_percentage); } qsort(arr, n, sizeof(struct Student), comparator); printf("\n\nStudent Records sorted by Name:\n"); for (int i = 0; i < n; i++) { printf("Id = %d, Name = %s, Age = %d \n", arr[i].student_id, arr[i].student_name, arr[i].student_percentage); } return 0; }
출력
Unsorted Student Record: Id = 1, Name = Nupur, Age = 98 Id = 2, Name = Akash, Age = 75 Id = 3, Name = Yash, Age = 62 Id = 4, Name = Jyoti, Age = 87 Id = 5, Name = Ramlal, Age = 80 Student Records sorted by Name: Id = 2, Name = Akash, Age = 75 Id = 4, Name = Jyoti, Age = 87 Id = 1, Name = Nupur, Age = 98 Id = 5, Name = Ramlal, Age = 80 Id = 3, Name = Yash, Age = 62