c - 对泛型结构类型数组进行排序

标签 c sorting struct

我有一个包含 id 和平均成绩的结构,我想对用户选择的数组进行排序,无论是按 id 还是按成绩

here is the struct

struct Stud {
    int id;
    float gradeAverage;
    float incomeAverage;
    int numOfGrades;
    struct gradeList *gradelist;
    struct incomeList *incomelist;
};

Students students[30];

i tried to use bubble sort but it didnt work any help please.

void Sort(void* array,int i, int len, int(*comp)(void *a, void *b), void(*swap)(void *a, void *b))
{
    int newlen;
    while (len != 0) {
        newlen = 0;
        for (int i = 1; i < len; i++) {
            if (!comp(array +i- 1, array + i)) {
                swap(array + i - 1, array + i);
                newlen = i;
            }
        }
        len = newlen;
    }
}

最佳答案

使用qsort()

制作比较功能

int comp(const void *a, const void *b) {
   Student *sa = a;
   Student *sb = b;
   if (BY_ID) return sa->id - sb->id;
   // otherwise, by num of grades
   return sa->numOfGrades - sb->numOfGrades;
}

调用qsort

#define N 30

qsort(students, N, sizeof(Student), comp);

结构也需要一些修复,例如

typedef struct Stud {
        int id;
        float gradeAverage;
        float incomeAverage;
        int numOfGrades;
        struct gradeList *gradelist;
        struct incomeList *incomelist;
} Student;

Student students[N];  // see #define above

可读性:Student 处没有“s”,因为它代表一个学生。

关于c - 对泛型结构类型数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47596849/

相关文章:

php - MYSQL ORDER BY 子句不起作用

c++ - Visual Studio 抛出异常 : write acces violation. q_deck->p_deck 为 0x110112。 C语言

c - 如何根据字符串的值访问 `struct' 的成员?

c - 如何将 C 中的 uint32_t 移植到 Windows 7(32 位)

c - 简单的指针查询,初始化一个指针

c - 使用空指针交换函数

c - 为什么 const 局部数组/结构在 c 中不是静态的?

firebase - 使用 Dart .sort() 函数对 AsyncSnapshot<QuerySnapshot<Object?>> 中的 Firebase 数据进行排序

python - 在包含格式为 ('hour' 、 'min' 、 'AM/PM' 的时间元组的列表中查找时间的最大值

c - 如何在 C 中实现位集