Question:

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 15, 2026
Hide Solution
collegedunia
Verified By Collegedunia

Correct Answer: 8

Solution and Explanation

Step 1: Understand the function.
The function compares adjacent elements.
If \( L[i]>L[i+1] \), it swaps them and returns 1 plus recursive calls.
This behaves like one pass of Bubble Sort and counts number of swaps in one full pass.
Step 2: Perform passes manually.
Initial list: \[ [5, 3, 4, 1, 2] \] First pass:
5>3 → swap → [3,5,4,1,2] (1)
5>4 → swap → [3,4,5,1,2] (2)
5>1 → swap → [3,4,1,5,2] (3)
5>2 → swap → [3,4,1,2,5] (4)
Swaps in first pass = 4
Second pass:
3>4 → no
4>1 → swap → [3,1,4,2,5] (1)
4>2 → swap → [3,1,2,4,5] (2)
4>5 → no
Swaps in second pass = 2
Third pass:
3>1 → swap → [1,3,2,4,5] (1)
3>2 → swap → [1,2,3,4,5] (2)
3>4 → no
4>5 → no
Swaps in third pass = 2
Fourth pass:
No swaps
Fifth pass:
No swaps
Step 3: Add total swaps.
\[ 4 + 2 + 2 = 8 \] Final Answer: \[ \boxed{8} \]
Was this answer helpful?
0
0

Top Questions on Data Structures and Algorithms

View More Questions