Hatim Hatim - 1 month ago 6
C Question

How to sort objects by a property in C language

I need to know how to change a property of each object in an array and sort that objects according to that property value. highest to lowest.

this is the program

typedef struct
{
char name[100];
int comp, math, phys, rank;
int total;

} student;


and created an array of students

student student1 ={"student1", 1, 1, 1, 0, 3}
student student ={"student2", 1, 2, 1, 0, 4}

student studentList[0] = student1;
student studentList[1] = student2;


now I have an array of students

how to change the "rank" of each object in the array, the highest total should has a rank of 1,

the code should be dynamic, means if the array length was 2 or 100, it doesn't matter

// change rank property of each object in a list


// print all students sorted by rank

Answer

change a property of each object in an array

Assuming this is your array: studentList[NUM_OF_STUDENTS] you do studentList[student_you_want_to_change].rank = new_rank;

sort that objects according to that property value. highest to lowest.

Simplest way would be bubble sort:

  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;
           }
       }
   }

note that bubble sort is the simplest to implement but it is not the fastest (you can use qsort or merge-sort instead if you would like

the code should be dynamic, means if the array length was 2 or 100, it doesn't matter

If so, use a pointer and after you get the size - create your array: `

scanf("%d",&NUM_OF_STUDENTS);    /* get size of array */ 
studentList = malloc(sizeof(student) * NUM_OF_STUDENTS);
Comments