Question 2581
After exactly 2 passes of this partial insertion sort, what is the array?
int[] arr = {8, 3, 5, 1, 4};
for (int i = 1; i < 3; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}Main Solution
Step-by-step trace of the code:
Initial array: {8, 3, 5, 1, 4}
Pass 1 (i = 1):
key = arr[1] = 3j = 0- While loop:
j >= 0(true) ANDarr[0] > key→8 > 3(true):arr[1] = arr[0]→ array becomes{8, 8, 5, 1, 4};j = -1 - While loop:
j >= 0(false) → exit arr[j + 1] = arr[0] = key = 3→ array becomes{3, 8, 5, 1, 4}
Pass 2 (i = 2):
key = arr[2] = 5j = 1- While loop:
j >= 0(true) ANDarr[1] > key→8 > 5(true):arr[2] = arr[1]→ array becomes{3, 8, 8, 1, 4};j = 0 - While loop:
j >= 0(true) ANDarr[0] > key→3 > 5(false) → exit arr[j + 1] = arr[1] = key = 5→ array becomes{3, 5, 8, 1, 4}
After exactly 2 passes, the array is {3, 5, 8, 1, 4}, which matches option B.
Teacher Explanation
This question tests students' ability to trace a partial insertion sort. The loop runs only for i = 1 and i = 2 (since i < 3), so only the first three elements get sorted among themselves. The last two elements (indices 3 and 4) remain untouched. After 2 passes, the subarray {8, 3, 5} becomes {3, 5, 8}, giving {3, 5, 8, 1, 4}.
Education Coach Advice
AP Exam Strategy: When tracing sorting algorithms, always track the exact loop bounds first. Here, i < 3 means only passes for i = 1 and i = 2 occur — only indices 0–2 are affected. Write out the array state after each pass to avoid errors. Elements beyond the loop's reach stay in their original positions.
Traps
Common traps:
- Option A ({1, 3, 5, 8, 4}): Students may think the entire array gets sorted or confuse the loop bound
i < 3with more passes, incorrectly including element1in the sorted portion. - Option C/D: Students may miscount the number of passes or misread the loop condition, thinking 4 or 5 passes occur instead of just 2.
Answer images

