使用 qsort 函数对 C 中的结构数组进行排序

Sorting an struct array in C with qsort function

首先,我看到了一些例子:

但它们对我不起作用。

我的结构是

typedef struct Team {
    int total;
    char name[N][N];   // Nombre
    int points[N];     // Points
    int pg[N];         // Won Matches
    int pe[N];         // Tied Matches
    int pp[N];         // Lost Matches
    int gf[N];         // Goals For 
    int gc[N];         // Goals Against
} Teams;

int compareTeams(struct Team *e1, struct Team *e2){
    int comparer;
    int dg1 = e1->gf - e1->gc;
    int dg2 = e2->gf - e2->gc;

    //classified according to the points
    if (e1->points > e2->points) {
        comparer=-1;
    } else if (e1->points < e2->points) {
        comparer=1;
    } else {
        // with the same points, goal difference check
        if (dg1 > dg2) {
            comparer=-1;
        } else if (dg1 < dg2) {
            comparer=1;
        } else {
            // with the same goal difference , we check who scored more goals
            if(e1->gf > e2->gf) {
                comparer=-1;
            } else if (e1->gf < e2->gf) {
                comparer=1;
            } else
                comparer=0;
        }
    }
    return comparer;
}

在主要功能中,我有这个:

Teams teams[100];
qsort(teams, teams->total, sizeof(struct Team), &compareTeams);

但显然,它不起作用:(

你只有一个结构:

typedef struct Team {
    int total;
    char name[N][N];   // Nombre
    int points[N];     // Points
    int pg[N];         // Won Matches
    int pe[N];         // Tied Matches
    int pp[N];         // Lost Matches
    int gf[N];         // Goals For 
    int gc[N];         // Goals Against
} Teams;

这个结构命名错误;它不是一个团队,它是一个联盟。除了 total 之外的所有字段本身都是数组。如果要对这个结构进行排序,则必须同时交换所有数组,因为它们本质上是独立的。 qsort 做不到;你将不得不编写自己的排序算法。

当您重组数据时,它使管理团队和排序变得更容易:团队应该只包含自己的数据:

typedef struct Team {
    char name[24];
    int points;               // Points
    int won, drawn, lost;     // Match records
    int scored, conceded;     // Goal records
} Teams;

然后你可以创建一个团队数组:

Team league[] = {
    {"FC Bayern Muenchen",   85,   27,  4,  2,   77, 16},
    {"Borussia Dortmubd",    77,   24,  5,  4,   80, 32},
    {"Bayer 04 Leverkusen",  57,   17,  6, 10,   53, 38},
    {"Borussia M'Gladbach",  52,   16,  4, 13,   65, 50},
    // ...
};

然后写一个比较函数来遵守qsort中使用的定义:

int compareTeams(const void *p1, const void *p2)
{
    const Team *e1 = p1;
    const Team *e2 = p2;

    int dg1 = e1->gf - e1->gc;
    int dg2 = e2->gf - e2->gc;

    if (e1->points > e2->points) return -1;
    if (e1->points < e2->points) return 1;

    if (dg1 > dg2) return -1;
    if (dg1 < dg2) return 1;

    if (e1->gf > e2->gf) return -1;
    if (e1->gf < e2->gf) return 1;

    return 0;
}

并使用它:

qsort(league,
    sizeof(league) / sizeof(*league),    // number of teams
    sizeof(*league),                     // size of one team
    compareTeams);

重组意味着每个团队的数据都保存在同一个结构中,而不是交换许多独立的数组以保持它们同步,而是交换整个团队。