Which of the following is best running time to sort \(π\) integers in theβ¦
2019
Which of the following is best running time to sortΒ \(π\)Β integers in the rangeΒ \(0\)Β to \(n^2-1\)?
- A.
\(π(log n)\) - B.
\(π(π)\) - C.
\(π(π log n)\) - D.
\(π(π^2)\)
Attempted by 131 students.
Show answer & explanation
Correct answer: B
Answer: O(n)
Explanation: The integers lie in the range 0 to n^2β1, so each integer can be represented in base n using at most two digits. Use a stable radix sort (least significant digit first) with counting sort as the stable subroutine.
Write each number in base n; each number has at most two digits (each digit is in 0..nβ1).
Use counting sort to sort by the least significant digit. Counting sort runs in O(n + base) = O(n) when base = n.
Use counting sort again to sort by the most significant digit. Because counting sort is stable, the two passes together yield a fully sorted list.
Total time: two passes of O(n) each, so overall O(n).
Why other answers are not best: Comparison-based sorts have a lower bound of Ξ©(n log n), so O(n log n) is the best among comparison sorts but is not optimal here because we exploit the integer representation. O(log n) is impossible because reading n elements needs Ξ©(n) time. O(n^2) is achievable by naive counting over the entire range but is worse than the radix approach.
A video solution is available for this question β log in and enroll to watch it.