The GATE Grind

GATE 2026 DA – Question 58

Programming, Data Structures and Algorithms · Programming in Python · 2 marks · Numerical answer

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*)

Practise this question in The GATE Grind →

Show answer and explanation

Correct answer: 8

Explanation

One call of fun is a single bubble sort pass: it swaps every adjacent pair that is out of order and returns the number of swaps. Pass 1 on [5, 3, 4, 1, 2] makes 4 swaps and gives [3, 4, 1, 2, 5]. Pass 2 makes 2 swaps and gives [3, 1, 2, 4, 5]. Pass 3 makes 2 swaps and gives [1, 2, 3, 4, 5]. The last two passes find nothing to swap. The total is $4 + 2 + 2 = 8$, which is the number of inversions in the original array.