Question

Suppose P, Q, R, S, T are sorted sequences having lengths 20, 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 _____.

Official answer and solution
Official answer
358
From
Official GATE 2014 answer key

Solution

Construct the optimal 2-way merge tree using Huffman's greedy algorithm and calculate worst-case comparisons at each merge step.

  1. Comparison Cost for Merging Two Lists:
    Merging two sorted lists of lengths mm and nn requires at most m+n−1m + n - 1 comparisons in the worst case.

  2. Optimal Merge Pattern (Greedy Selection):
    Always merge the two shortest available lists at each step.
    Initial list sizes: {20,24,30,35,50}\{20, 24, 30, 35, 50\}.

    • Step 1: Merge 20 and 24:

      New size=20+24=44.\text{New size} = 20 + 24 = 44.
      Comparisons=20+24−1=43.\text{Comparisons} = 20 + 24 - 1 = 43.

      Available sizes: {30,35,44,50}\{30, 35, 44, 50\}.

    • Step 2: Merge 30 and 35:

      New size=30+35=65.\text{New size} = 30 + 35 = 65.
      Comparisons=30+35−1=64.\text{Comparisons} = 30 + 35 - 1 = 64.

      Available sizes: {44,50,65}\{44, 50, 65\}.

    • Step 3: Merge 44 and 50:

      New size=44+50=94.\text{New size} = 44 + 50 = 94.
      Comparisons=44+50−1=93.\text{Comparisons} = 44 + 50 - 1 = 93.

      Available sizes: {65,94}\{65, 94\}.

    • Step 4: Merge 65 and 94:

      New size=65+94=159.\text{New size} = 65 + 94 = 159.
      Comparisons=65+94−1=158.\text{Comparisons} = 65 + 94 - 1 = 158.
  3. Total Worst-Case Comparisons:

    Total=43+64+93+158=358.\text{Total} = 43 + 64 + 93 + 158 = 358.
Final answer

358

Common trap

Calculating record movement cost (m + n) instead of comparison cost (m + n - 1), which would mistakenly give 362.

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 2
Question
48 of 65, printed as CS Q.38
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.