Unit 4 Cycle 2 Day 13: Array: In-Place Reversal

Unit 4 Advanced (Cycle 2) Day 13 of 28 Advanced

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.

int[] arr = {1, 2, 3, 4, 5}; for (int i = 0; i < arr.length / 2; i++) { int temp = arr[i]; arr[i] = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = temp; } System.out.println(arr[1] + " " + arr[3]);

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.

Review this topic: Section 4.3 — Common Array Algorithms • Unit 4 Study Guide
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.