ProgrammingHardGATE CS · Campus placements
struct P { int id; int score; }; An array must be sorted by score descending, with ties broken by id ascending, using qsort. Which comparator is correct?
- A. return b->score - a->score;
- B. return a->id - b->id;
- C. if (a->score != b->score) return b->score > a->score ? 1 : -1; return a->id - b->id;
- D. return a->score > b->score;
Correct answer: C. if (a->score != b->score) return b->score > a->score ? 1 : -1; return a->id - b->id;
When scores differ, the element with the larger score must come first, so the comparator returns 1 when b has the bigger score. Equal scores fall through to the id tie-break. The first option ignores ties, and the last returns only 0 or 1, which is not a valid three-way comparison.
More C Programming questions
- For a = {2, 4, 2, 2, 6, 4}, how many index pairs i < j satisfy a[i] == a[j]?
- uint32t fact(uint32t n) { return n <= 1 ? 1 : n fact(n - 1); } What does fact(13) return?
- uint8t acc = 0; uint8t a[3] = {250, 3, 7}; for each element, acc += a[i]; What is acc after all three additions?
- int a[] = {3, 5, 6, 9}; int pre[5]; pre[0] = 0, and pre[i] = pre[i-1] ^ a[i-1] for i = 1..4. What is pre[4] ^ pre[1]?
- void f(int a) { sizet n = sizeof a / sizeof a[0]; ... } is called as f(arr) where int arr[4]. What is true about n?
- unsigned int n = 0u; int i = 0; if (i < n - 1) printf("loop"); What is printed?