Question

Let PP be a quicksort program to sort numbers in ascending order using the first element as the pivot. Let t1t_1 and t2t_2 be the number of comparisons made by PP for the inputs [1 2 3 4 5][1\ 2\ 3\ 4\ 5] and [4 1 5 3 2][4\ 1\ 5\ 3\ 2] respectively. Which one of the following holds?

Choose one option
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: [1,2,3,4,5][1, 2, 3, 4, 5] (already sorted array):

  • First call on [1,2,3,4,5][1, 2, 3, 4, 5]: pivot 1 is compared with 4 remaining elements (4 comparisons). Subarrays: empty and [2,3,4,5][2, 3, 4, 5].
  • Second call on [2,3,4,5][2, 3, 4, 5]: pivot 2 is compared with 3 elements (3 comparisons). Subarrays: empty and [3,4,5][3, 4, 5].
  • Third call on [3,4,5][3, 4, 5]: pivot 3 is compared with 2 elements (2 comparisons). Subarrays: empty and [4,5][4, 5].
  • Fourth call on [4,5][4, 5]: pivot 4 is compared with 1 element (1 comparison).
    Total comparisons t1=4+3+2+1=10t_1 = 4 + 3 + 2 + 1 = 10 (worst-case behavior).

Input 2: [4,1,5,3,2][4, 1, 5, 3, 2]:

  • First call on [4,1,5,3,2][4, 1, 5, 3, 2]: pivot 4 is compared with 4 elements (1,5,3,21, 5, 3, 2). Elements smaller than 4 are {1,3,2}\{1, 3, 2\} and larger are {5}\{5\}. (4 comparisons).
  • Subarray [1,3,2][1, 3, 2]: pivot 1 is compared with 2 elements (3,23, 2). Both are larger, so {3,2}\{3, 2\}. (2 comparisons).
  • Subarray [3,2][3, 2]: pivot 3 is compared with 1 element (22). (1 comparison).
  • Subarray of size 1 ([5][5]): 0 comparisons.
    Total comparisons t2=4+2+1=7t_2 = 4 + 2 + 1 = 7.

Comparing t1t_1 and t2t_2:

t1=10>7=t2t_1 = 10 > 7 = t_2

Hence, t1>t2t_1 > t_2.

Final answer

C

Common trap

Assuming quicksort always does O(nlog⁡n)O(n \log n) 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.