简体   繁体   中英

Sorting a struct type array generic

I have a struct that contains id and grade average i want to sort the array genericaly the user choises wether by its id or by grades

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

Use qsort()

Make the comparison function

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

Call qsort

#define N 30

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

The structure needs some fix as well, eg

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

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

Readability: No 's' at Student, since it represents one student.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM