ProgrammingVery hardTCS NQT · Accenture

What is printed?

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

Correct answer: B. 8 3 5 7

Popcounts are 3 for 7, 1 for 8, and 2 for both 3 and 5. The order is 8, then 3 and 5 by value, then 7.

More C Programming questions

Exams that ask this topic