How to sort an array of structs in the C language?
In C language, you can use the standard library function qsort() to sort arrays of structures. qsort() is a fast sorting function in the C standard library that requires a comparison function for determining the order of elements.
Here is an example demonstrating how to use the qsort() function to sort an array of structures based on a certain attribute.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义结构体
struct student {
char name[20];
int age;
float score;
};
// 比较函数
int compare(const void *a, const void *b) {
struct student *studentA = (struct student *)a;
struct student *studentB = (struct student *)b;
// 按照年龄升序排序
if (studentA->age < studentB->age)
return -1;
else if (studentA->age > studentB->age)
return 1;
else
return 0;
}
int main() {
struct student students[3];
// 初始化结构体数组
strcpy(students[0].name, "Alice");
students[0].age = 20;
students[0].score = 85.6;
strcpy(students[1].name, "Bob");
students[1].age = 18;
students[1].score = 92.3;
strcpy(students[2].name, "Charlie");
students[2].age = 22;
students[2].score = 78.9;
// 使用qsort()函数进行排序
qsort(students, 3, sizeof(struct student), compare);
// 打印排序后的结果
for (int i = 0; i < 3; i++) {
printf("Name: %s, Age: %d, Score: %.1f\n", students[i].name, students[i].age, students[i].score);
}
return 0;
}
In the example above, we defined a struct called student, which includes three attributes: name, age, and score. We then defined a comparison function compare() to compare the ages of two structs. In the main() function, we initialized a struct array called students containing three students, and used the qsort() function to sort them. Finally, we printed the sorted result.
Note that when using the qsort() function to sort, you need to provide the size of each element (sizeof(struct student)) and a comparison function. The comparison function should return an integer value that indicates the relationship between two elements. A return value less than 0 indicates the first element is less than the second element, a return value greater than 0 indicates the first element is greater than the second element, and a return value equal to 0 indicates that the two elements are equal. In this example, we are sorting in ascending order by age, so the comparison function will compare based on the age attribute.