pointers-memory · intermediate · ~15 min

Multi-key struct comparator for qsort

Cast generic void pointers and implement multi-key tie-breaking for qsort.

Challenge

The standard C qsort() function accepts a function pointer int (*cmp)(const void *, const void *). To sort complex structures, the comparator must cast the generic void* arguments and implement multi-level tie-breaking.

Your Task

Implement:

struct employee {
    int id;
    int score;
    char name[32];
};

int employee_cmp(const void *a, const void *b);

Sorting Order

Sort employees:

  1. Primary: by score in descending order (highest score first).
  2. Secondary (Tie-breaker): by id in ascending order (lowest id first).
  3. If both score and id match, return 0.

Return Values

  • Return < 0 if a should precede b.
  • Return > 0 if b should precede a.
  • Return 0 if a and b are considered equivalent.

Input format

a, b: generic const void* pointers to struct employee instances.

Output format

Returns negative, zero, or positive integer for qsort.

Constraints

C11 freestanding comparator. Cast void* safely.

Starter code

#include <stddef.h>

/* The harness provides:
struct employee {
    int id;
    int score;
    char name[32];
};
*/

int employee_cmp(const void *a, const void *b) {
    (void)a; (void)b;
    return 0;
}

Common mistakes

Subtracting scores directly leading to signed integer overflow; sorting ascending instead of descending for score.

Edge cases to handle

Identical scores tie-break on id; identical score and id return 0; negative scores.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.