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

Correct Answer: 8

Approach Solution - 1

To solve the problem, we need to understand the functioning of the given Python code snippet: 

  • The function fun(L, i=0) returns the number of adjacent swaps required to sort the list L in non-decreasing order, starting from the index i.
  • The iteration in for _ in range(len(data)) repeatedly calls fun(data) and accumulates the swap count in count.

Let's walk through the code step-by-step:

  1. The code initializes the list data = [5, 3, 4, 1, 2].
  2. In the function fun(L, i=0), it checks if the current index i is the last or beyond. If so, it returns 0.
  3. If L[i] > L[i+1], a swap occurs between L[i] and L[i+1], and the function returns 1 plus the swap count from the next index.
  4. If no swap is needed, it calls itself with the next index.
  5. This recursive function aims to sort the list using adjacent swaps, counting swaps each time it iterates.

The outer loop repeatedly calls fun(data) len(data) times to ensure complete sorting, aggregating the swap count.

Given the expected result is within the range (8, 8), let's analyze if our code achieves this:

  • Initial data: [5, 3, 4, 1, 2]
  • Swaps: [3, 5, 4, 1, 2], [3, 4, 5, 1, 2], [3, 4, 1, 5, 2], [3, 4, 1, 2, 5], [3, 1, 4, 2, 5], [3, 1, 2, 4, 5], [1, 3, 2, 4, 5], [1, 2, 3, 4, 5]
  • Total swaps needed: 8

The computed swap count is 8, fitting exactly within the provided range.

Thus, the output is:

8

 

Was this answer helpful?
0
0
Hide Solution
collegedunia
Verified By Collegedunia

Approach Solution -2

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

Questions Asked in GATE DA exam

View More Questions