我需要知道如何更改数组中每个对象的属性并根据该属性值对对象进行排序。从最高到最低。
这是程序
typedef struct
{
char name[100];
int comp, math, phys, rank;
int total;
} student;
并创建了一批学生
student student1 ={"student1", 1, 1, 1, 0, 3}
student student ={"student2", 1, 2, 1, 0, 4}
student studentList[0] = student1;
student studentList[1] = student2;
现在我有很多学生
如何更改数组中每个对象的“排名”,最高的总排名应为 1,
代码应该是动态的,意味着如果数组长度是2或100,都没关系
// change rank property of each object in a list
// print all students sorted by rank
最佳答案
change a property of each object in an array
假设这是您的数组:studentList[NUM_OF_STUDENTS]
,您会studentList[student_you_want_to_change].rank = new_rank;
sort that objects according to that property value. highest to lowest.
最简单的方法是冒泡排序:
for(i = 0; i < NUM_OF_STUDENTS; i++){
for(j = 0; j < NUM_OF_STUDENTS; j++){
if(studentList[i].rank > studentList[j].rank){
// swap
tmp = studentList[j].rank;
studentList[j].rank = studentList[i].rank;
studentList[i].rank = tmp;
}
}
}
请注意,冒泡排序是最简单的实现方式,但它并不是最快的(如果您愿意,可以使用 qsort 或归并排序来代替
the code should be dynamic, means if the array length was 2 or 100, it doesn't matter
如果是这样,请使用指针,并在获得大小后 - 创建数组:`
scanf("%d",&NUM_OF_STUDENTS); /* get size of array */
studentList = malloc(sizeof(student) * NUM_OF_STUDENTS);
关于c - C语言中如何按属性对对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40276259/