sorting an array of structures by 2 parameters

502 views Asked by At

I have a structure

struct employee {
    int record;
    int ID;
....
};

employee * arr = (employee*) malloc(501 * sizeof (employee));

And i need to sort it by this two parameters (ID at first and record as the second). I'm using standart Qsort with

 qsort (employee, records, sizeof(employee), compare);

But i dont know, how to edit basic compare function, to make it works

I have samething like this

int comparestruct(const employee *p1, const employee *p2)
{
    const struct employee *elem1 = p1;    
    const struct employee *elem2 = p2;

   if ( elem1->ID < elem2->ID)
      return -1;
   else if (elem1->ID > elem2->ID)
      return 1;
   else
      return 0;
}

But this isn't working...

Any help please?

1

There are 1 answers

0
Chris Dodd On BEST ANSWER

The usual way would be something like:

int comparestruct(const void *a_, const void *b_) {
    const struct employee *a = a_;
    const struct employee *b = b_;
    int rv = a->ID - b->ID;
    if (rv == 0) rv = a->record - b->record;
    return rv;
}

Of course, this has a subtle bug if the subtractions might overflow (which depends on the range of your IDs and record numbers.) If that is a possible problem, you might need:

int comparestruct(const void *a_, const void *b_) {
    const struct employee *a = a_;
    const struct employee *b = b_;
    if (a->ID < b->ID) return -1;
    if (a->ID > b->ID) return 1;
    if (a->record < b->record) return -1;
    if (a->record > b->record) return 1;
    return 0;
}

instead