Unit 4 Cycle 2 Day 23: Broken In-Place Reversal

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

Broken In-Place Reversal

Section 4.5 — ArrayList Algorithms

Key Concept

A broken in-place reversal is a common AP exam error-spotting scenario. Typical bugs include: swapping all elements instead of only the first half (which swaps them back), using the wrong boundary condition, not using a temporary variable for the swap (losing one value), or using length instead of length - 1 for the right index. The AP exam presents a reversal algorithm with one subtle error and asks you to identify what goes wrong or what incorrect output is produced.

Consider the following code segment.

ArrayList list = new ArrayList(); for (int i = 1; i <= 5; i++) list.add(i * 10); for (int i = 0; i < list.size(); i++) list.set(i, list.get(list.size() - 1 - i)); System.out.println(list);

What is printed?

Answer: (B) [50, 40, 30, 40, 50]

Initial: [10,20,30,40,50]. i=0: set(0, get(4))=50: [50,20,30,40,50]. i=1: set(1, get(3))=40: [50,40,30,40,50]. i=2: set(2, get(2))=30: unchanged. i=3: set(3, get(1))=40: already 40. i=4: set(4, get(0))=50: already 50.

Why Not the Others?

(A) Would be correct reversal, but overwrites destroy data.

(C) First elements get last values, not the other way around.

(D) The list IS modified.

Common Mistake

In-place reversal fails without temp variables. set() overwrites values needed later. The second half reads already-modified values. Use swap or a temp variable.

AP Exam Tip

This broken reversal is a classic AP exam trap. Overwritten values cannot be recovered. Always use a temp variable or build a new list.

Review this topic: Section 4.5 — ArrayList Algorithms • Unit 4 Study Guide
Back to blog

Leave a comment

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