ProgrammingHardGATE CS · Campus placements

struct P { int id; int score; }; An array must be sorted by score descending, with ties broken by id ascending, using qsort. Which comparator is correct?

  1. A. return b->score - a->score;
  2. B. return a->id - b->id;
  3. C. if (a->score != b->score) return b->score > a->score ? 1 : -1; return a->id - b->id;
  4. D. return a->score > b->score;

Correct answer: C. if (a->score != b->score) return b->score > a->score ? 1 : -1; return a->id - b->id;

When scores differ, the element with the larger score must come first, so the comparator returns 1 when b has the bigger score. Equal scores fall through to the id tie-break. The first option ignores ties, and the last returns only 0 or 1, which is not a valid three-way comparison.

More C Programming questions

Exams that ask this topic