Question 2871
After one pass of this code, what is arr[arr.length - 1]?
int[] arr = {2, 5, 1, 8, 3};
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}Main Solution
This code performs one pass of a bubble sort over the array {2, 5, 1, 8, 3}. Let's trace through each iteration:
- i = 0: Compare
arr[0]=2andarr[1]=5. 2 < 5, no swap. Array:{2, 5, 1, 8, 3} - i = 1: Compare
arr[1]=5andarr[2]=1. 5 > 1, swap. Array:{2, 1, 5, 8, 3} - i = 2: Compare
arr[2]=5andarr[3]=8. 5 < 8, no swap. Array:{2, 1, 5, 8, 3} - i = 3: Compare
arr[3]=8andarr[4]=3. 8 > 3, swap. Array:{2, 1, 5, 3, 8}
After one full pass, arr[arr.length - 1] = arr[4] = 8. This is a key property of bubble sort: after one pass, the largest element "bubbles up" to the last position.
The correct answer is C) 8.
Teacher Explanation
This question tests students' understanding of one pass of bubble sort. The key insight is that after one complete pass through the array, the maximum element is guaranteed to be in the last position. Students must trace through all four comparisons carefully, noting that only two swaps occur (at i=1 and i=3), and that the value 8 ends up at index 4.
Education Coach Advice
AP Exam Strategy: When tracing array manipulation code, write out the array state after each iteration. For bubble sort questions specifically, remember that one pass always moves the largest unseen element to its correct final position. This saves time and prevents errors from trying to hold the entire state in your head.
Traps
Common traps:
- Option A (3): Students might think the last element stays as the original last element (3), forgetting that swaps can move it.
- Option B (5): Students might stop tracing early or miscalculate which swaps occur.
- Option D (2): Students might confuse the first and last elements or misread the loop direction.
The most appealing wrong answer is likely A (3), since 3 is the original last element and students may not realize it gets swapped with 8 during the last iteration.
Answer images

