Unit 4 Cycle 2 Day 13: Array: In-Place Reversal
Share
Array: In-Place Reversal
Section 4.3 — Common Array Algorithms
Key Concept
In-place array reversal swaps elements from both ends moving inward. The pattern uses two indices: left starting at 0 and right starting at arr.length - 1. Each iteration swaps arr[left] and arr[right], then moves both indices inward. The loop stops when left >= right. A common error is processing too many iterations (swapping elements back to their original positions). The AP exam tests whether you correctly handle both even and odd length arrays.
Consider the following code segment.
What is printed?
Answer: (B) 4 2
Reverse: swap from outside in. Result: {5, 4, 3, 2, 1}. arr[1]=4, arr[3]=2.
Why Not the Others?
(A) 2 4 are the original values before reversal.
(C) The middle stays 3, but indices 1 and 3 get swapped values.
(D) 5 1 are arr[0] and arr[4], not indices 1 and 3.
Common Mistake
In-place reversal: swap arr[i] with arr[length-1-i]. Loop to length/2.
AP Exam Tip
Reversal pattern: swap outer pairs working inward. The temp variable prevents data loss during swap.