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]);
}- A. 1203 1105 1101 0FFF 0102
- B. 0102 0FFF 1101 1105 1203
- C. 1203 1101 1105 0FFF 0102
- 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
- What is printed? c #include <stdio.h> unsigned sumd(unsigned n) { return n == 0 ? 0 : n % 10 + sumd(n / 10); } int main(void) {…
- How many subsets of {1, 2, 3, 4, 5, 6} (the empty set included) have a sum divisible by 3? Compute with this program. c #include <stdio.h>…
- What is printed by the first two calls? c #include <stdio.h> unsigned next(void) { static unsigned s = 1; s = s 1103515245u + 12345u…
- What is printed? c #include <stdio.h> int main(void) { int total = 0; for (unsigned x = 1; x <= 100; x++) { unsigned y = x; while (y) {…
- What is printed? c #include <stdio.h> #include <string.h> int main(void) { const char names[] = {"ann", "bob", "cat", "dan", "eve"}; const…
- What is printed? Assume long long is 64 bits and that the product fits in a long long. c #include <stdio.h> int main(void) { long long p =…