asdasd
asdasd

Reputation: 59

Qsort to sort array of structs

I am trying to sort an array of structs with qsort. However I am having problems with understanding how to make the compare function. I have the following struct:

typedef struct {
  char name[TEAM_SIZE];
  int points;
} TEAM;

And I am trying to sort each team after its points with the highest first.

qsort(team, NUMBER_OF_TEAMS, sizeof(team), compare_points);

And the compare function:

int compare_points(const void *a, const void *b) {
  TEAM *p1 = (TEAM *)a;
  TEAM *p2 = (TEAM *)b;

  if(p1->points < p2->points) {
    return 1;
  }
  else {
    return -1;
  }
}

How would you do this?

Output:

Before:FCN 38
Before:FCM 59
Before:OB 46
Before:AGF 37
Before:AAB 50
Before:FCK 71
Before:HOB 18
Before:SDR 62
Before:RFC 47
Before:BIF 54
Before:EFB 30
Before:VFF 40
After:FCM 59
After 8
After:OB 46
After:AGF 37
After:AAB 50
After:FCK 71
After:HOB 18
After:SDR 62
After:RFC 47
After:BIF 54
After:EFB 30
After:VFF 40

Upvotes: 0

Views: 116

Answers (1)

John Bollinger
John Bollinger

Reputation: 180398

Your qsort() call is wrong:

qsort(team, NUMBER_OF_TEAMS, sizeof(team), compare_points);

The third argument must be the size of each element of the array. You are passing instead either the size of the whole array or the size of a pointer, depending on how team is declared. You want:

qsort(team, NUMBER_OF_TEAMS, sizeof(TEAM), compare_points);

Also, your comparison function is slightly flawed in that it returns -1 when p1->points == p2->points. Inasmuch as you seem to be sorting on the points member, your comparison function should return 0 when two teams have the same number of points.

Example

#include <stdio.h>
#include <stdlib.h>

#define TEAM_SIZE 10

typedef struct {
    char name[TEAM_SIZE];
    int points;
} TEAM;


int compare_points(const void *a, const void *b)
{
    const TEAM *p1 = a;
    const TEAM *p2 = b;
    return p2->points < p1->points ? -1 : p1->points < p2->points;
}

int main()
{
    TEAM teams[] =
    {
        { "OB",  46 }, { "AGF", 37 },
        { "AAB", 50 }, { "FCK", 71 },
        { "HOB", 18 }, { "SDR", 62 },
        { "RFC", 47 }, { "BIF", 54 },
        { "EFB", 30 }, { "VFF", 40 }
    };

    size_t NUM_TEAMS = sizeof teams / sizeof *teams;

    qsort(teams, NUM_TEAMS, sizeof(TEAM), compare_points);

    for (size_t i=0; i< NUM_TEAMS; ++i)
        printf("%s : %d\n", teams[i].name, teams[i].points);

    return 0;
}

Output

FCK : 71
SDR : 62
BIF : 54
AAB : 50
RFC : 47
OB : 46
VFF : 40
AGF : 37
EFB : 30
HOB : 18

See it live here.

Upvotes: 4

Related Questions