我有一个包含id和等级平均值的结构我想根据用户的id或等级选择通用的数组
这是结构
struct Stud {
int id;
float gradeAverage;
float incomeAverage;
int numOfGrades;
struct gradeList *gradelist;
struct incomeList *incomelist;
};
Students students[30];
我尝试使用冒泡排序,但它没有任何帮助。
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;
}
}
答案 0 :(得分:1)
使用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
可读性:没有&#39;&#39;在学生,因为它代表一个学生。