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\)?

  1. A.

    \(𝑂(log n)\)

  2. B.

    \(𝑂(𝑛)\)

  3. C.

    \(𝑂(𝑛 log n)\)

  4. 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.

  1. Write each number in base n; each number has at most two digits (each digit is in 0..nβˆ’1).

  2. Use counting sort to sort by the least significant digit. Counting sort runs in O(n + base) = O(n) when base = n.

  3. 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.

Explore the full course: Coding For Placement