Skip to content
Official PYQ · 2014

GATE CS 2014 Set 1 Q14 — Searching, Sorting, Hashing

Explain with AI

Let PP be 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 P 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
View worked solution

Answer: C

For a quicksort implementation that uses the first element as the pivot:

Case 1: Input [1,2,3,4,5][1, 2, 3, 4, 5]
Since the input is already sorted, choosing the first element as the pivot results in the worst-case partitioning:
• Pivot 11: compared with 2,3,4,52, 3, 4, 5 (44 comparisons). Remaining: [2,3,4,5][2, 3, 4, 5].
• Pivot 22: compared with 3,4,53, 4, 5 (33 comparisons). Remaining: [3,4,5][3, 4, 5].
• Pivot 33: compared with 4,54, 5 (22 comparisons). Remaining: [4,5][4, 5].
• Pivot 44: compared with 55 (11 comparison).
Total comparisons t1=4+3+2+1=10t_1 = 4 + 3 + 2 + 1 = 10.

Case 2: Input [4,1,5,3,2][4, 1, 5, 3, 2]
• Pivot 44: compared with 1,5,3,21, 5, 3, 2 (44 comparisons). Partitions into [1,3,2][1, 3, 2] and [5][5].
• For [5][5]: 00 comparisons.
• For [1,3,2][1, 3, 2]: Pivot 11 is compared with 3,23, 2 (22 comparisons). Partitions into [][] and [3,2][3, 2].
• For [3,2][3, 2]: Pivot 33 is compared with 22 (11 comparison).
Total comparisons t2=4+2+1=7t_2 = 4 + 2 + 1 = 7.

Since t1=10t_1 = 10 and t2=7t_2 = 7, we have t1>t2t_1 > t_2.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Searching, Sorting, Hashing questions