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)
8.00
Step-by-Step Solution
Insight: The inner function fun performs one left-to-right pass of adjacent swaps, returning the number of swaps. The outer loop calls it n times, which is exactly the Bubble Sort algorithm. The total number of swaps in Bubble Sort equals the number of inversions in the initial array.
Exam route: Count the inversions in [5, 3, 4, 1, 2]. 5 is greater than 3, 4, 1, 2 (4 inversions). 3 is greater than 1, 2 (2 inversions). 4 is greater than 1, 2 (2 inversions). Total = 4 + 2 + 2 = 8.
Learning route:
Pass 1: [5, 3, 4, 1, 2] -> 5 bubbles to the end. Swaps: (5,3), (5,4), (5,1), (5,2). Count = 4. Array: [3, 4, 1, 2, 5].
Pass 2: [3, 4, 1, 2, 5] -> 4 bubbles to index 3. Swaps: (4,1), (4,2). Count = 2. Array: [3, 1, 2, 4, 5].
Pass 3: [3, 1, 2, 4, 5] -> 3 bubbles to index 2. Swaps: (3,1), (3,2). Count = 2. Array: [1, 2, 3, 4, 5].
Pass 4 & 5: Already sorted, 0 swaps.
Total count = 4 + 2 + 2 + 0 + 0 = 8.