Question
Let be a quicksort program to sort numbers in ascending order using the first element as the pivot. Let and be the number of comparisons made by for the inputs and respectively. Which one of the following holds?
Official answer and solution
- Official answer
- C
- From
- Official GATE 2014 answer key
Solution
Trace quicksort with the first element as pivot on both inputs and compare the number of comparisons made.
Quicksort uses the first element of each subarray as the pivot.
Input 1: (already sorted array):
- First call on : pivot 1 is compared with 4 remaining elements (4 comparisons). Subarrays: empty and .
- Second call on : pivot 2 is compared with 3 elements (3 comparisons). Subarrays: empty and .
- Third call on : pivot 3 is compared with 2 elements (2 comparisons). Subarrays: empty and .
- Fourth call on : pivot 4 is compared with 1 element (1 comparison).
Total comparisons (worst-case behavior).
Input 2: :
- First call on : pivot 4 is compared with 4 elements (). Elements smaller than 4 are and larger are . (4 comparisons).
- Subarray : pivot 1 is compared with 2 elements (). Both are larger, so . (2 comparisons).
- Subarray : pivot 3 is compared with 1 element (). (1 comparison).
- Subarray of size 1 (): 0 comparisons.
Total comparisons .
Comparing and :
Hence, .
C
Assuming quicksort always does comparisons regardless of the input order.
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2014 Computer Science and Information Technology (CS) Session 1
- Question
- 24 of 65, printed as CS Q.14
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.