ProgrammingHardTCS NQT · Accenture

A struct R has int16t score and uint8t id. After qsort with cmp below, what is printed?

A struct R has int16_t score and uint8_t id. After qsort with cmp below, what is printed?
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
struct R { int16_t score; uint8_t id; };
int cmp(const void *p, const void *q) {
    const struct R *a = p, *b = q;
    if (a->score != b->score) return a->score < b->score ? 1 : -1;
    return (int)a->id - (int)b->id;
}
int main(void) {
    struct R r[] = {{70,3},{90,1},{70,1},{90,2},{55,9}};
    qsort(r, 5, sizeof r[0], cmp);
    for (int i = 0; i < 5; i++) printf("%d/%d ", r[i].score, r[i].id);
}
  1. A. 90/2 90/1 70/3 70/1 55/9
  2. B. 55/9 70/1 70/3 90/1 90/2
  3. C. 90/1 90/2 70/3 70/1 55/9
  4. D. 90/1 90/2 70/1 70/3 55/9

Correct answer: D. 90/1 90/2 70/1 70/3 55/9

The comparator sorts by score descending and then id ascending, and every (score, id) pair is distinct, so the order is fully determined. Reversing the sign of the score test gives the ascending list.

More C Programming questions

Exams that ask this topic