ProgrammingVery hardCompetitive coding (CP)

After sorting by squared distance from the origin, with ties broken by x ascending, what is printed?

After sorting by squared distance from the origin, with ties broken by x ascending, what is printed?
#include <stdio.h>
#include <stdlib.h>
struct P { int x, y; };
int cmp(const void *a, const void *b) {
    const struct P *p = a, *q = b;
    int dp = p->x * p->x + p->y * p->y, dq = q->x * q->x + q->y * q->y;
    if (dp != dq) return dp - dq;
    return p->x - q->x;
}
int main(void) {
    struct P v[] = {{3, 4}, {0, 5}, {1, 1}, {2, 2}};
    qsort(v, 4, sizeof v[0], cmp);
    for (int i = 0; i < 4; i++) printf("%d %d ", v[i].x, v[i].y);
}
  1. A. 1 1 2 2 0 5 3 4
  2. B. 0 5 1 1 2 2 3 4
  3. C. 1 1 2 2 3 4 0 5
  4. D. 2 2 1 1 0 5 3 4

Correct answer: A. 1 1 2 2 0 5 3 4

Squared distances are 25, 25, 2 and 8. After (1,1) and (2,2), the two points at distance squared 25 are ordered by x, so (0,5) precedes (3,4).

More C Programming questions

Exams that ask this topic