GATE DA 2026 · Bubble Sort

NAT · 2 marks · Problem PROG-SORT-0017

Consider the given Python program. def fun(L, i=0): if i >= len(L)-1: return 0
    if L[i] > L[i+1]:
        L[i+1], L[i] = L[i], L[i+1]
        return 1+fun(L, i+1)
    else:
        return fun(L, i+1)
data = [5, 3, 4, 1, 2]
count = 0
for _ in range(len(data)):
    count += fun(data)
print(count) The output of the program is ________. (Answer in integer ) \rule{2.5cm}{0.4pt}

Numerical answer (NAT).

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

Show the worked solution\(\text{fun}(L,i)\) compares adjacent elements \(L[i],L[i+1]\), swaps them (and counts \(1\)) if out of order, then recurses to \(i+1\) — this is exactly one bubble-sort pass, counting the swaps made in that pass. The outer loop runs this fresh pass \(5\) times (since \(\text{len(data)}=5\)), accumulating the swap count each time.\(\text{data}=[5,3,4,1,2]\):Pass 1: \((5,3)\to\)swap, \((5,4)\to\)swap, \((5,1)\to\)swap, \((5,2)\to\)swap \(\Rightarrow[3,4,1,2,5]\), \(4\) swaps.Pass 2: \((3,4)\) no swap, \((4,1)\to\)swap, \((4,2)\to\)swap, \((4,5)\) no swap \(\Rightarrow[3,1,2,4,5]\), \(2\) swaps.Pass 3: \((3,1)\to\)swap, \((3,2)\to\)swap, \((3,4)\) no swap, \((4,5)\) no swap \(\Rightarrow[1,2,3,4,5]\), \(2\) swaps.Passes 4, 5: array already sorted, \(0\) swaps each.Total \(\text{count}=4+2+2+0+0=8\)Answer: 8Click Here for Detail SolutionGateOverflow discussion: https://gateoverflow.in/523166/gate-da-2026-question-48

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