ProgrammingHard
To find the k-th largest of 10^6 records by score, which approach is correct and fast enough?
- A. Full bubble sort on all records, O(N^2)
- B. Nested loops comparing every pair, O(N^2)
- C. Quickselect or a min-heap of size k, about O(N log k) or O(N) on average
- D. Insertion sort on the whole array, O(N^2) moves
Correct answer: C. Quickselect or a min-heap of size k, about O(N log k) or O(N) on average
A heap of size k or quickselect avoids the quadratic work. At N = 10^6, N^2 is about 10^12 operations and is far too slow within a typical limit.
More C Programming questions
- To find duplicate keys among 2 x 10^5 records, which method is correct and fast enough?
- A qsort comparator must sort records by name in descending order using strcmp on char name[16] fields. Which is correct?
- An array of 10^6 records of 100 bytes each must be sorted. Which approach is correct and fast enough?
- struct S { int id; int v; }; struct S a[4] = {{1,9},{2,8},{3,7},{4,6}}; struct S b[4]; memcpy(b, a, sizeof a); b[0].v = 0; printf("%d %d"…
- struct Grid { int cell[2][2]; }; struct Grid g1 = {{{1, 2}, {3, 4}}}; struct Grid g2 = g1; g2.cell[1][1] = 0; printf("%d", g1.cell[1][1])…
- Which is the correct way to count distinct keys in a sorted struct array a[0..n-1] (n >= 1) by key?