给结构体数组用sort函数排序C语言
时间: 2025-06-29 17:05:53 浏览: 9
在C语言中,可以使用标准库函数`qsort`来对结构体数组进行排序。`qsort`函数定义在`stdlib.h`头文件中,它使用快速排序算法对数组进行排序。
首先,你需要定义一个比较函数,该函数用于比较两个结构体元素的大小。比较函数应该接受两个`const void*`类型的参数,并返回一个整数。如果第一个参数小于第二个参数,则返回负值;如果两者相等,则返回0;如果第一个参数大于第二个参数,则返回正值。
下面是一个简单的例子,演示如何使用`qsort`对结构体数组进行排序:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int id;
float score;
} Student;
// 比较函数,根据分数score进行升序排序
int compare(const void *a, const void *b) {
Student *studentA = (Student *)a;
Student *studentB = (Student *)b;
if (studentA->score < studentB->score) return -1;
else if (studentA->score > studentB->score) return 1;
else return 0;
}
int main() {
Student students[] = {{1, 92.5}, {2, 88.0}, {3, 74.5}, {4, 95.0}};
int n = sizeof(students) / sizeof(students[0]);
// 使用qsort排序
qsort(students, n, sizeof(Student), compare);
// 打印排序后的结果
for (int i = 0; i < n; i++) {
printf("ID: %d, Score: %.1f\n", students[i].id, students[i].score);
}
return 0;
}
```
在这个例子中,我们定义了一个`Student`结构体,包含学生的ID和分数。我们创建了一个`Student`数组,并使用`qsort`函数对其进行排序。排序的依据是学生的分数,通过自定义的比较函数`compare`实现。最后,我们遍历并打印排序后的数组。
阅读全文
相关推荐


















