Difficulty: Medium
Correct Answer: 0 9 3 6 5
Explanation:
Introduction / Context:
This follow-up uses the same static-index idea but performs the swap before recursion. The base condition is j != i
, so recursion stops when the two indices meet at the center. You must trace the swaps carefully with persistent i, j
to get the final array ordering.
Given Data / Assumptions:
[5, 6, 3, 9, 0]
.i = 0
, j = 4
.arr[i]
with arr[j]
, then increments i
and decrements j
.
Concept / Approach:
Because the swap occurs immediately, we reverse pairs from the outermost inward, then stop when i == j
. With static variables, each recursive frame sees updated indices rather than independent copies.
Step-by-Step Solution:
[0, 6, 3, 9, 5]
; then i=1
, j=3
; recurse (1 != 3).Call 2: swap 1↔3 → [0, 9, 3, 6, 5]
; then i=2
, j=2
; stop (2 == 2).Display prints: 0 9 3 6 5
.
Verification / Alternative check:
Compare with the variant that swaps after recursion; you will notice the middle positions differ because of the different order of operations.
Why Other Options Are Wrong:
Common Pitfalls:
Thinking that recursion will reverse the entire array including the center twice; the stopping condition prevents that.
Final Answer:
0 9 3 6 5
Discussion & Comments