ProgrammingVery hardCompetitive coding (CP)

A qsort comparator must order the uint16t values by high byte descending and, for equal high bytes, by low byte ascending. What is printed?

A qsort comparator must order the uint16_t values by high byte descending and, for equal high bytes, by low byte ascending. What is printed?
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) {
    int x = *(const uint16_t *)a, y = *(const uint16_t *)b;
    int hx = x >> 8, hy = y >> 8;
    if (hx != hy) return hy - hx;
    return (x & 0xFF) - (y & 0xFF);
}
int main(void) {
    uint16_t v[] = {0x1203, 0x1101, 0x0102, 0x1105, 0x0FFF};
    qsort(v, 5, sizeof v[0], cmp);
    for (int i = 0; i < 5; i++) printf("%04X ", (unsigned)v[i]);
}
  1. A. 1203 1105 1101 0FFF 0102
  2. B. 0102 0FFF 1101 1105 1203
  3. C. 1203 1101 1105 0FFF 0102
  4. D. 1203 1101 1105 0102 0FFF

Correct answer: C. 1203 1101 1105 0FFF 0102

Sorting by high byte descending puts 12, then 11, then 0F, then 01. The two entries with high byte 11 are ordered by their low bytes, 01 before 05.

More C Programming questions

Exams that ask this topic