ProgrammingVery hard
To sort 10^6 integers with qsort, which comparator is correct for all int values?
- A. static int cmp(const void *a, const void *b) { int x = *(const int *)a, y = *(const int *)b; return (x > y) - (x < y); }
- B. static int cmp(const void *a, const void *b) { return *(const int *)a - *(const int *)b; }
- C. static int cmp(const void *a, const void *b) { return *(const long *)a - *(const long *)b; }
- D. static int cmp(const void *a, const void *b) { return abs(*(const int *)a - *(const int *)b); }
Correct answer: A. static int cmp(const void *a, const void *b) { int x = *(const int *)a, y = *(const int *)b; return (x > y) - (x < y); }
The subtraction version overflows for large values of opposite sign, which is undefined. The boolean version never returns negative values, so qsort cannot order correctly.
More C Programming questions
- A counting pass over an array of 10^7 values, each in [0, 9], uses 10 counters. Which statement is correct?
- Which output method is fast enough for 10^6 lines of output in C?
- Which 2D DP table declaration is correct for a 1000 x 1000 table of ints in a contest C program?
- A modular sum over 10^6 terms uses sum = (sum + a[i]) % MOD with a[i] < MOD and sum an int. What is wrong?
- A counting loop uses the expression i i <= n with int i and n up to 2^31 - 1. Is the loop correct?
- To read a whole line of unknown length in standard C without overflow, which approach is correct?