Quicksort on sorted input — Aptitude Question
Quicksort on sorted input: Quicksort always takes the first element as its pivot. What is its running time on an… Answer and worked solution on CodeKairo.
- Topic: Data Structures & Algorithms
- Section: Programming MCQs
- Difficulty: Easy
- Time target: 60 seconds
Question
Quicksort always takes the first element as its pivot. What is its running time on an array that is already sorted in ascending order?
Options
- O(log n)
- O(n)
- O(n log n)
- O(n²)
Show the answer and the worked solution
Correct answer: D. O(n²)
Worked solution
- On sorted input the first element is the smallest, so partitioning leaves nothing on the left and n − 1 elements on the right.
- The recursion therefore strips off one element at a time and reaches depth n.
- The work at each level is proportional to the size still being processed, so the total is n + (n − 1) + … + 1, which is about n²/2 and hence O(n²).
Answer: O(n²).
The idea
Quicksort is fast when partitions are balanced and quadratic when they are not. Choosing a random pivot or the median of three makes the sorted-input worst case vanishingly unlikely.
Shortcut. Sorted input with a first-element pivot is quicksort's textbook worst case: every split is 0 against n − 1, so the recursion is n deep with linear work per level.
Common trap. "O(n log n)" is quicksort's average case, quoted without checking that this pivot rule makes every partition lopsided.
All Data Structures & Algorithms questions · placement mock tests