ProgrammingVery hardCompetitive coding (CP)

What is printed?

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

Correct answer: D. 1 -2 3 4 -5

The comparator orders by absolute value, so the absolute values 1, 2, 3, 4, 5 give 1, -2, 3, 4, -5 with the signs kept. Dropping the signs in the output gives 1 2 3 4 5.

More C Programming questions

Exams that ask this topic