Difficulty: Medium
Correct Answer: 0 6 3 9 5
Explanation:
Introduction / Context:
This problem checks your ability to trace a recursive function that uses static indices and performs its swap operations after unwinding recursion. The order of operations (pre-recursion index update, then post-recursion swap) is crucial to the final arrangement of the array elements.
Given Data / Assumptions:
[5, 6, 3, 9, 0]
.i = 0
, j = 4
.i
, decrements j
, recurses while j > 0
, then swaps arr[i]
and arr[j]
while unwinding.
Concept / Approach:
Because the swap happens after recursion returns, the deepest frame swaps the ends first, then higher frames swap inner pairs, potentially swapping some positions back depending on indices restored by the static variables. Carefully tracking the evolving values of i
and j
is the key.
Step-by-Step Solution:
[0, 6, 3, 9, 5]
; i=3
, j=1
.Next: swap indices 3 and 1 → [0, 9, 3, 6, 5]
; i=2
, j=2
.Next: swap indices 2 and 2 (no change) → remains [0, 9, 3, 6, 5]
; i=1
, j=3
.Next: swap indices 1 and 3 → [0, 6, 3, 9, 5]
; i=0
, j=4
.
Verification / Alternative check:
Compare with a version that performs the swap before recursion; it yields a different ordering (see next question for a variant).
Why Other Options Are Wrong:
Common Pitfalls:
Forgetting that i
and j
are static and persist across frames; assuming each function activation has its own i, j
.
Final Answer:
0 6 3 9 5
Discussion & Comments