51 lines
1.4 KiB
C
51 lines
1.4 KiB
C
#include "c_InsertionSort.h"
|
|
#include <stdlib.h>
|
|
#include <stdio.h>
|
|
|
|
typedef struct {
|
|
int id;
|
|
char name[20];
|
|
double score;
|
|
} Student;
|
|
|
|
// 自定义比较函数:按成绩 (score) 降序排列
|
|
// 如果希望升序,只需反转返回值或改变比较符号
|
|
int compareStudentsByScoreDesc(const void* a, const void* b) {
|
|
const Student* s1 = (const Student*)a;
|
|
const Student* s2 = (const Student*)b;
|
|
|
|
if (s1->score > s2->score) return -1; // s1 成绩高,排在前面
|
|
if (s1->score < s2->score) return 1; // s1 成绩低,排在后面
|
|
return 0;
|
|
}
|
|
|
|
int main(int argc, char* argv[]) {
|
|
// 准备一个无序的学生数组
|
|
Student students[] = {
|
|
{101, "Alice", 82.5},
|
|
{105, "Bob", 95.0},
|
|
{109, "Charlie", 88.0},
|
|
{112, "David", 79.5}
|
|
};
|
|
size_t count = sizeof(students) / sizeof(students[0]);
|
|
|
|
printf("排序前:\n");
|
|
for (size_t i = 0; i < count; i++) {
|
|
printf("学号: %d, 姓名: %s, 成绩: %.1f\n", students[i].id, students[i].name, students[i].score);
|
|
}
|
|
|
|
// 调用通用插入排序
|
|
c_InsertionSort(
|
|
students,
|
|
count,
|
|
sizeof(Student),
|
|
compareStudentsByScoreDesc
|
|
);
|
|
|
|
printf("\n排序后(按成绩降序):\n");
|
|
for (size_t i = 0; i < count; i++) {
|
|
printf("学号: %d, 姓名: %s, 成绩: %.1f\n", students[i].id, students[i].name, students[i].score);
|
|
}
|
|
|
|
return 0;
|
|
} |