Skip to content
Official PYQ · 2014

GATE CS 2014 Set 2 Q38 — Searching, Sorting, Hashing

Explain with AI
Suppose P,Q,R,S,TP, Q, R, S, T are sorted sequences having lengths 20,24,30,35,5020, 24, 30, 35, 50 respectively. They are to be merged into a single sequence by merging together two sequences at a time. The number of comparisons that will be needed in the worst case by the optimal algorithm for doing this is ____.
View worked solution

Answer: 358

To find the minimum number of comparisons in the worst case to merge multiple sorted sequences, we use an optimal merge pattern (similar to Huffman's greedy approach).

Key Principle

When merging two sorted sequences of sizes mm and nn, the number of comparisons required in the worst case is:

Comparisons=m+n−1\text{Comparisons} = m + n - 1

To minimize the total number of comparisons, we greedily select the two smallest sequences at each step to merge.

Step-by-Step Merging

The initial sizes of the sequences are: {20,24,30,35,50}\{20, 24, 30, 35, 50\}.

  1. Merge the two smallest sequences: 2020 and 2424.
    • New sequence size: 20+24=4420 + 24 = 44
    • Worst-case comparisons: 20+24−1=4320 + 24 - 1 = 43
    • Remaining sizes: {30,35,44,50}\{30, 35, 44, 50\}
  2. Merge the two smallest sequences: 3030 and 3535.
    • New sequence size: 30+35=6530 + 35 = 65
    • Worst-case comparisons: 30+35−1=6430 + 35 - 1 = 64
    • Remaining sizes: {44,50,65}\{44, 50, 65\}
  3. Merge the two smallest sequences: 4444 and 5050.
    • New sequence size: 44+50=9444 + 50 = 94
    • Worst-case comparisons: 44+50−1=9344 + 50 - 1 = 93
    • Remaining sizes: {65,94}\{65, 94\}
  4. Merge the remaining two sequences: 6565 and 9494.
    • New sequence size: 65+94=15965 + 94 = 159
    • Worst-case comparisons: 65+94−1=15865 + 94 - 1 = 158

Total Comparisons

Summing the comparisons from each step:

Total Comparisons=43+64+93+158=358\text{Total Comparisons} = 43 + 64 + 93 + 158 = 358

Thus, the minimum number of comparisons needed in the worst case is 358.

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

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