GATE DA 2024 | Question 41

MCQ · 2 marks · −0.66

Consider the following Python function:

def fun(D, s1, s2):
       if s1 < s2:
          D[s1], D[s2] = D[s2], D[s1]
          fun(D, s1+1, s2-1)

What does this Python function fun() do? Select the ONE appropriate option below.

  1. Option A: It finds the smallest element in D from index s1 to s2, both inclusive.
  2. Option B: It performs a merge sort in-place on this list D between indices s1 and s2, both inclusive.
  3. Option C: It reverses the list D between indices s1 and s2, both inclusive. (correct)
  4. Option D: It swaps the elements in D at indices s1 and s2, and leaves the remaining elements unchanged.

Answer

(C)

Explanation

Each call swaps the two outer elements D[s1] and D[s2], then recurses on the next pair inward, s1+1 and s2-1. It stops when the indices meet or cross, so the middle element of an odd-length range stays where it is.

For example, with D = [1, 2, 3, 4, 5], fun(D, 0, 4) swaps 1 and 5, then 2 and 4, giving [5, 4, 3, 2, 1]: the segment from s1 to s2 is reversed in place.

Option D describes only the first call, but the recursion keeps swapping the inner pairs. The function never compares values, so it cannot find a minimum (A) or sort (B).

Answer: C