ProgrammingHardTCS CodeVita · Infosys HackWithInfy

Timsort is the algorithm behind Python's sorted(). For an input that is already in ascending order, what is its running time?

  1. A. O(log n), because only the first element needs comparing
  2. B. O(n), because Timsort detects the existing run and does almost no comparisons beyond one pass
  3. C. O(n log n), the same as the worst case
  4. D. O(n^2), because the input is sorted

Correct answer: B. O(n), because Timsort detects the existing run and does almost no comparisons beyond one pass

Timsort finds natural runs in one linear pass. A fully sorted input is a single run, so it needs about n - 1 comparisons, which is the best case O(n).

More Python Programming questions

Exams that ask this topic