• edited by
806 views
0 0 votes

Consider the given Python program.

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)

1 Answer

3 3 votes
Solution:

Given function:

\[
\texttt{fun(L, i=0)}
\]

In the loop, the function is called as

\[
\texttt{fun(data)}
\]

Since the second argument is not passed, the default value \( i=0 \) is used every time the function is called.

Thus, for each new call inside the loop, \( i \) is reinitialized to 0.

However, the list data  is modified in-place and retains its updated values.

 

The function compares adjacent elements and swaps them if they are out of order.

It then recursively proceeds to the next index.

 

Thus, one call to fun(data) performs exactly one left-to-right pass of Bubble Sort and returns the number of swaps in that pass.

Initial list:

\[
[5, 3, 4, 1, 2]
\]

The outer loop runs 5 times, so Bubble Sort performs 5 passes.

Pass 1 (i = 0):

\[
[5,3,4,1,2] \rightarrow [3,4,1,2,5]
\]

Swaps = 4

Pass 2 (i = 1):

\[
[3,4,1,2,5] \rightarrow [3,1,2,4,5]
\]

Swaps = 2

Pass 3 (i = 2):

\[
[3,1,2,4,5] \rightarrow [1,2,3,4,5]
\]

Swaps = 2

Pass 4 (i = 3):

Already sorted.

Swaps = 0

Pass 5 (i = 4):

Already sorted.

Swaps = 0

Total swaps:

\[
4 + 2 + 2 + 0 + 0 = 8
\]

Shortcut Method:

In Bubble Sort, the total number of swaps equals the number of inversions in the original array.

An inversion is a pair \( (i,j) \) such that \( i<j \) and \( L[i] > L[j] \).

For the array

\[
[5,3,4,1,2]
\]

The inversions are:

\[
(5,3), (5,4), (5,1), (5,2),
(3,1), (3,2),
(4,1), (4,2)
\]

Total inversions = 8.

Therefore, the output of the program is

\[
\boxed{8}
\]
• moved by
Answer:
Position:
Show:

Related questions

1 1 vote
1 1 answer
620
620 views
gatecse asked Feb 23
620 views
Consider the given Python program.def append_to_lst(val, lst=[]): lst.append(val) return lst print(append_to_lst(1)) print(append_to_lst(2)) print(append_to_lst(3, []))Wh...
2 2 votes
5 5 answers
955
955 views
gatecse asked Feb 23
955 views
​​​​​​A recursive function in Python is given.def mystery(n): if n <= 0: return 1 else: return mystery(n-1) + mystery(n-2)Now, consider the following function call:myster...
1 1 vote
1 1 answer
575
575 views
gatecse asked Feb 23
575 views
Consider the given Python program.def outer(): x = [] def inner(val): x.append(val) return x return inner f1 = outer() f2 = outer() print(f1(10)) # Line P print(f1(20)) #...
6 6 votes
1 1 answer
470
470 views
GO Classes asked Jul 1
470 views
Consider the following Python code:def virfib_sq(n): print(n) if n <= 1: return n return (virfib_sq(n - 1) + virfib_sq(n - 2)) 2 r4 = virfib_sq(4)What would be the outp...