Question:medium

Given the Python code: 

Show Hint

This recursive function performs one full Bubble Sort pass and counts swaps. Total swaps across all passes equals the inversion count of the array.
Updated On: Feb 16, 2026
Show Solution

Correct Answer: 8

Solution and Explanation

Step 1: Understanding the Topic
This question requires analyzing a recursive Python function and tracing its execution within a loop. The function `fun` iterates through a list, compares adjacent elements, and performs swaps, which is characteristic of the Bubble Sort algorithm. The function also returns a count of the swaps it performs in a single pass.
Step 2: Key Approach - Tracing Bubble Sort Passes
The code initializes a list `data`. The `for` loop calls the `fun` function `len(data)` times. Each call to `fun(data)` performs one pass of the Bubble Sort algorithm on the `data` list (which is modified in-place) and returns the number of swaps made during that pass. The variable `count` accumulates the total number of swaps over all passes.
Step 3: Detailed Explanation
Initial list: `data = [5, 3, 4, 1, 2]` Total swap `count` = 0. The loop will run 5 times.

Pass 1 (Loop 1): `fun(data)` is called.

5>3: swap. List: `[3, 5, 4, 1, 2]`. Swaps: 1.
5>4: swap. List: `[3, 4, 5, 1, 2]`. Swaps: 2.
5>1: swap. List: `[3, 4, 1, 5, 2]`. Swaps: 3.
5>2: swap. List: `[3, 4, 1, 2, 5]`. Swaps: 4.
`fun` returns 4. `count` becomes $0 + 4 = 4$. List is now `[3, 4, 1, 2, 5]`.
Pass 2 (Loop 2): `fun(data)` is called again.

3<4: no swap.
4>1: swap. List: `[3, 1, 4, 2, 5]`. Swaps: 1.
4>2: swap. List: `[3, 1, 2, 4, 5]`. Swaps: 2.
4<5: no swap.
`fun` returns 2. `count` becomes $4 + 2 = 6$. List is now `[3, 1, 2, 4, 5]`.
Pass 3 (Loop 3): `fun(data)` is called.

3>1: swap. List: `[1, 3, 2, 4, 5]`. Swaps: 1.
3>2: swap. List: `[1, 2, 3, 4, 5]`. Swaps: 2.
`fun` returns 2. `count` becomes $6 + 2 = 8$. List is now `[1, 2, 3, 4, 5]`.
Pass 4 (Loop 4): `fun(data)` is called. The list is now sorted. No adjacent elements are out of order. No swaps will occur. `fun` returns 0. `count` becomes $8 + 0 = 8$.
Pass 5 (Loop 5): `fun(data)` is called. List is still sorted. `fun` returns 0. `count` becomes $8 + 0 = 8$.
Step 4: Final Answer
After the loop finishes, the final value of `count` is 8, which is then printed. \[ \boxed{8} \]
Was this answer helpful?
0