Master Mathematics.

Programming · Recursion, Divide & Conquer, Greedy & DP · Problem 2

Counting swaps in recursive bubble passes

Consider

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 is .

Source: GATE DA