Curated · Divide & Conquer: Mergesort

NAT · 2 marks · Problem PROG-DIVC-0274

Consider the following Python code.
c = 0
def msort(a):
    global c
    if len(a) <= 1:
        return a
    L, R = msort(a[:len(a) // 2]), msort(a[len(a) // 2:])
    out, i, j = [], 0, 0
    while i < len(L) and j < len(R):
        c += 1
        if L[i] <= R[j]:
            out.append(L[i]); i += 1
        else:
            out.append(R[j]); j += 1
    return out + L[i:] + R[j:]
msort([3, 8, 1, 6, 2, 4, 5, 7])
print(c)
The value printed is .

Numerical answer (NAT).

Solve it on GATE DA practice →More Searching & Sorting Algorithms problems

Show the worked solution\[\boxed{\text{a merge stops comparing as soon as one side is used up}}\]Pairs: \((3,8), (1,6), (2,4), (5,7)\) take 1 comparison each: 4.\([3,8]\) with \([1,6]\): outputs 1, 3, 6 by comparison, then 8 is copied: 3.\([2,4]\) with \([5,7]\): outputs 2, 4 by comparison, then 5, 7 are copied: 2.\([1,3,6,8]\) with \([2,4,5,7]\): outputs 1 to 7 by comparison, then 8 is copied: 7.\(c = 4 + 3 + 2 + 7 = 16\), one less than the worst case 17 for 8 elements.Answer: 16

GATE DA practice: past exam problems by chapter, with worked solutions · gatedaprep.com