ProgrammingHardTCS NQT · Accenture

What is printed?

What is printed?
#include <stdio.h>
#include <stdlib.h>
struct Pair { int a, b; };
int cmp(const void *p, const void *q) {
    const struct Pair *x = p, *y = q;
    if (x->b != y->b) return y->b - x->b;
    return x->a - y->a;
}
int main(void) {
    struct Pair v[] = {{1, 5}, {2, 9}, {3, 5}, {4, 1}};
    qsort(v, 4, sizeof v[0], cmp);
    for (int i = 0; i < 4; i++) printf("%d ", v[i].a);
}
  1. A. 2 1 3 4
  2. B. 2 3 1 4
  3. C. 2 1 4 3
  4. D. 1 2 3 4

Correct answer: A. 2 1 3 4

The comparator sorts by b descending, so b = 9 comes first, then the two entries with b = 5 are ordered by a ascending, and b = 1 comes last. The printed a values are 2, 1, 3, 4.

More C Programming questions

Exams that ask this topic