GATE DA 2026, Q.58: Total swaps counted by a recursive bubble pass
The question
What does the code below print?
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)Watch it solved
Solve it step by step
- What fun does. One bubble-sort pass from left to right, returning the number of swaps.
- Pass 1. [5, 3, 4, 1, 2] → [3, 4, 1, 2, 5]: 4 swaps.
- Pass 2. → [3, 1, 2, 4, 5]: 2 swaps. Pass 3 → [1, 2, 3, 4, 5]: 2 swaps.
- Passes 4 and 5. No swaps. Total 4 + 2 + 2 = 8, the number of inversions.
Answer: 8
Official IIT Guwahati answer key: 8.
Common mistake. Counting comparisons instead of swaps.
Remember. Total bubble-sort swaps = number of inversions in the array.
Want every question solved? The past-paper pack has all 195 questions from 2024, 2025 and 2026 for ₹499. The cheat sheet pack has 23 printable sheets for ₹399.
See the past-paper pack See the cheat sheetsSource: official GATE DA 2026 question paper and answer key (IIT Guwahati). The question is lightly reworded; every number and option is kept.