Implementing Selection and Iteration Algorithms
Help Questions
AP Computer Science A › Implementing Selection and Iteration Algorithms
Given the task requirements, which of the following correctly implements the required loop structure?
Implement insertion sort to sort an integer array in ascending order. Use iteration to shift larger elements to the right, and selection to decide when shifting stops.
Input: $n$, then $n$ integers.
Output: the sorted array.
Constraints: $1 \le n \le 100$; values in -1000, 1000.
Example input:
4
5 2 9 1
Example output:
1 2 5 9
Choose the correct inner loop for insertion sort (assume key = a<u>i</u> and j = i - 1):
while (j>=0 && a[j]>key) { a[j]=a[j+1]; j--; }
while (j>=0 && a[j]>key) { a[j+1]=a[j]; j--; }
while (j>=0 || a[j]>key) { a[j+1]=a[j]; j--; }
while (j>0 && a[j]<key) { a[j+1]=a[j]; j--; }
Explanation
This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on the inner loop logic of insertion sort for shifting elements. Insertion sort maintains a sorted portion and inserts each new element by shifting larger elements right until finding the correct position. In this scenario, the task requires implementing the shifting phase where elements larger than the key are moved one position right, starting from position j and moving leftward. Choice A (while (j>=0 && a[j]>key) { a[j+1]=a[j]; j--; }) is correct because it checks j>=0 to avoid array bounds errors, uses && to ensure both conditions are met, checks a[j]>key to shift only larger elements, correctly shifts with a[j+1]=a[j], and decrements j to move left. Choice C is incorrect because || would cause array access errors when j<0, and Choice D incorrectly assigns a[j]=a[j+1] which moves elements left instead of right. To help students: Visualize insertion sort as making space for the key by shifting elements right. Practice tracing the algorithm with small arrays and emphasize the importance of && versus || in compound conditions.
Based on the problem description, which of the following correctly implements the required loop structure?
Implement binary search on a sorted integer array to find the index of target. Use iteration to repeatedly narrow the search range and selection (if/else) to choose whether to search left or right. If not found, output -1.
Input: $n$, then $n$ sorted integers, then target.
Output: index of target or -1.
Constraints: $1 \le n \le 1000$; values in -100000, 100000.
Example input:
5
1 4 7 9 12
9
Example output:
3
Choose the correct loop condition for binary search (assume low and high are indices):
while (low == high)
while (low >= high)
while (low < high)
while (low <= high)
Explanation
This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on the correct loop condition for binary search implementation. Binary search requires maintaining a valid search range and must handle the case where low and high indices meet at the target element. In this scenario, the task requires implementing binary search which repeatedly narrows the search range by comparing the middle element with the target and adjusting low or high accordingly. Choice B (while (low <= high)) is correct because it continues searching while there's at least one element in the range (when low equals high, there's still one element to check), and properly terminates when low > high indicates an empty range meaning the target wasn't found. Choice A (while (low < high)) is incorrect because it would miss checking the case where low equals high, potentially failing to find elements that happen to be at that single remaining position. To help students: Trace binary search with small arrays, especially edge cases with 1-2 elements. Emphasize that low <= high maintains the invariant that the search range is valid and non-empty.
Given the task requirements, what will be the output after executing the provided code snippet?
You are implementing a linear search on an array of integers to find the first index of a target value. If the target is not found, output -1. Use iteration to scan the array and selection to stop when found.
Input: $n$, then $n$ integers, then target.
Output: the first index of target, or -1.
Constraints: $1 \le n \le 200$; integers in -1000, 1000.
Example input:
5
3 7 7 2 9
7
Example output:
1
Code snippet:
int[] a = {3, 7, 7, 2, 9};
int target = 7;
int idx = -1;
**for** (int i = 0; i < a.length; i++) {
**if** (a<u>i</u> == target) {
idx = i;
**break**;
}
}
System.out.print(idx);
-1
0
1
2
Explanation
This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on linear search with early termination using break statements. Linear search examines elements sequentially until finding the target or reaching the end, and the break statement provides efficient early exit when the target is found. In this scenario, the task requires finding the first occurrence of target value 7 in the array {3, 7, 7, 2, 9}, which appears at index 1 (0-based indexing). Choice B (1) is correct because the loop starts at i=0, checks a[0]=3 (not equal to 7), then checks a[1]=7 (equals target), sets idx=1, and breaks out of the loop, resulting in output 1. Choice A (0) would be incorrect as that's where 3 is located, and Choice C (2) would be the second occurrence of 7, but break ensures we stop at the first. To help students: Trace through the code step-by-step with actual values, emphasizing how break immediately exits the loop. Practice distinguishing between finding first occurrence versus all occurrences of a target value.
Given the task requirements, what will be the output after executing the provided code snippet?
You are implementing selection sort. After each outer-loop pass, the smallest remaining element is swapped into position i. Use iteration for scanning and selection for tracking the minimum.
Input: $n$, then $n$ integers.
Output: sorted array.
Constraints: $1 \le n \le 100$; values in -1000,1000.
Example input:
4
5 2 9 1
Example output:
1 2 5 9
Code snippet:
int[] a = {5, 2, 9, 1};
**for** (int i = 0; i < a.length - 1; i++) {
int min = i;
**for** (int j = i + 1; j < a.length; j++) {
**if** (a<u>j</u> < a<u>min</u>) {
min = j;
}
}
int tmp = a<u>i</u>;
a<u>i</u> = a<u>min</u>;
a<u>min</u> = tmp;
}
System.out.print(a<u>0</u> + " " + a<u>1</u>);
2 1
5 2
1 2
1 5
Explanation
This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on selection sort implementation and understanding its state after partial execution. Selection sort works by finding the minimum element in the unsorted portion and swapping it into the next sorted position, building the sorted array from left to right. In this scenario, the array {5, 2, 9, 1} undergoes selection sort, and we need to determine the first two elements after the algorithm completes. Choice A (1 2) is correct because in the first pass (i=0), the algorithm finds the minimum 1 at index 3 and swaps it with 5, giving {1, 2, 9, 5}; in the second pass (i=1), it finds minimum 2 already at index 1 so no swap occurs; after all passes, the sorted array is {1, 2, 5, 9}, so a[0]=1 and a[1]=2. Choice D (1 5) might tempt students who think only one pass occurs, but the loop continues for all necessary passes. To help students: Trace selection sort step-by-step, showing the array state after each outer loop iteration. Emphasize that selection sort makes n-1 passes for an n-element array, progressively building the sorted portion from the left.
Given the task requirements, identify the error in the following if-else implementation.
You are implementing selection sort on an integer array to sort it in ascending order. The algorithm must use iteration to find the smallest remaining value and selection to update the current minimum index.
Input: first an integer $n$, then $n$ integers.
Output: the sorted array on one line, space-separated.
Constraints: $1 \le n \le 100$; each integer is in -1000, 1000.
Example input:
4
5 2 9 1
Example output:
1 2 5 9
Code snippet inside the inner loop:
**if** (arr<u>j</u> < arr<u>minIndex</u>) {
minIndex = j;
} **else if** (arr<u>j</u> > arr<u>minIndex</u>) {
minIndex = j; // intended: do nothing
}
Comparison should be arr[j] == arr[minIndex]
Must use while instead of if
Second branch wrongly updates minIndex
Missing semicolon after minIndex = j
Explanation
This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on proper if-else logic within selection sort implementation. Selection sort works by finding the minimum element in the unsorted portion and swapping it with the first unsorted element, requiring careful tracking of the minimum index. In this scenario, the task requires correctly updating minIndex only when a smaller element is found, but the else if branch incorrectly updates minIndex when a larger element is found. Choice A is correct because the second branch (else if) wrongly updates minIndex when arr[j] > arr[minIndex], which would cause the algorithm to track the maximum instead of minimum, breaking the sorting logic. Choice B is incorrect because semicolons are not required after assignment statements in Java, and Choice C is incorrect because if statements are appropriate here - we don't need repeated checking with while. To help students: Emphasize that in selection sort, we only update minIndex when finding a smaller value, never for larger values. Practice tracing through the algorithm step-by-step to understand when and why index updates occur.
Based on the problem description, what will be the output after executing the provided code snippet?
You are processing student grades to compute an average. The program reads grades until -1. It should ignore the sentinel and compute the average of entered grades. Use selection to avoid dividing by zero when no grades were entered.
Input: integers ending with -1.
Output: "No grades" or average.
Constraints: grades in 0,100; at most 200 grades.
Example input:
-1
Example output:
No grades
Code snippet:
int sum = 0;
int count = 0;
int grade = -1;
**do** {
grade = scan.nextInt();
**if** (grade != -1) {
sum += grade;
count++;
}
} **while** (grade != -1);
**if** (count == 0) {
System.out.print("No grades");
} **else** {
System.out.print((double) sum / count);
}
If the input is just -1, what is printed?
0.0
Runtime error
No grades
-1.0
Explanation
This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on do-while loops and conditional output based on input validation. The do-while loop always executes at least once before checking the condition, which is crucial for reading input before testing it. In this scenario, when input is just -1, the do-while loop executes once: it reads -1, the if condition (grade != -1) is false so nothing is added to sum or count, then the while condition (grade != -1) is false so the loop exits with count=0. Choice B ("No grades") is correct because after the loop, count equals 0, so the if (count == 0) condition is true, printing "No grades" as required when no valid grades were entered. Choice A (0.0) would occur if count > 0 but sum = 0, which doesn't happen here since no grades were processed. To help students: Trace do-while loops carefully, noting they always execute once. Emphasize the importance of handling edge cases like empty input and practice identifying when counters remain at initial values.
You are implementing insertion sort for a small classroom tool that sorts quiz scores. The program reads $n$ integers into an array (unsorted), then sorts ascending using insertion sort. It must use iteration with a for loop for the outer pass and a while loop to shift elements. Input: first line $n$, second line $n$ integers. Output: the sorted array on one line separated by spaces. Constraints: $1 \le n \le 50$; values are in $-1000, 1000$.
Given the task requirements, which of the following correctly implements the required inner loop structure?
for (int i = 1; i < arr.length; i++) {
int key = arr<u>i</u>;
int j = i - 1;
// inner loop here
}
while (j >= 0 || arr[j] > key) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key;
while (j > 0 && arr[j] > key) { arr[j] = arr[j - 1]; j--; } arr[j] = key;
while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key;
while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j++; } arr[j + 1] = key;
Explanation
This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on insertion sort's inner loop mechanics within Java coding tasks. Insertion sort requires shifting elements rightward to make space for the key element, using a while loop that continues as long as we haven't reached the beginning of the array AND the current element is greater than the key. In this scenario, the task requires correctly implementing the shifting mechanism where elements are moved one position to the right until the correct insertion point is found. Choice A is correct because it properly implements both conditions (j >= 0 && arr[j] > key) with logical AND, shifts elements correctly (arr[j + 1] = arr[j]), decrements j to move left, and places the key at the correct position (arr[j + 1] = key). Choice C is incorrect due to using logical OR (||) instead of AND (&&), which would cause the loop to continue even when j becomes negative, resulting in an array index out of bounds error. To help students: Use visualization tools to show how elements shift during insertion sort, and emphasize the importance of compound conditions in preventing array access errors. Practice tracing the algorithm with small arrays to understand the shifting pattern.
You are implementing binary search for a library kiosk. The program reads a sorted array of $n$ integers (book codes) and a target code. It must use iteration (while) and selection to narrow the search: compare target to middle element and adjust low/high accordingly. Input: first line $n$, second line $n$ sorted integers, third line target. Output: index if found, else -1. Constraints: $1 \le n \le 100$; codes are 0–9999.
Given the task requirements, which of the following correctly implements the required loop update when target is less than mid value?
int low = 0, high = arr.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (target == arr<u>mid</u>) return mid;
else if (target < arr<u>mid</u>) {
// update here
} else {
low = mid + 1;
}
}
return -1;
high = mid + 1;
low = mid - 1;
high = mid - 1;
low = mid;
Explanation
This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on binary search boundary updates within Java coding tasks. Binary search narrows the search space by comparing the target with the middle element and adjusting either the low or high boundary accordingly, eliminating half of the remaining elements each iteration. In this scenario, when the target is less than arr[mid], we know the target must be in the left half of the current range, so we need to update high to exclude the right half including mid itself. Choice A (high = mid - 1) is correct because it properly implements the search space reduction by setting high to one position before mid, excluding all elements from mid onwards since they are all greater than or equal to arr[mid]. Choice B (high = mid + 1) is incorrect as it would expand the search range rightward instead of narrowing it leftward when target is smaller. To help students: Use visual representations of arrays with low, mid, and high pointers to show how the search space shrinks, and emphasize that we can exclude mid itself since we've already checked it. Practice tracing binary search with specific examples to understand boundary movements.
You are writing a grade-processing program for a teacher. The program reads $n$ integer scores (0–100) into an array and then prints each student's letter grade and the class average. Letter grades are assigned using selection: if score >= 90 then 'A', else if >= 80 then 'B', else if >= 70 then 'C', else if >= 60 then 'D', else 'F'. The program must use iteration to (1) read scores, (2) compute the sum, and (3) print results. Input format: first line $n$, second line contains $n$ scores separated by spaces. Output format: one line per student in the form "score: letter", then a final line "avg: X" where X is the average as a double with one decimal. Constraints: $0 \le n \le 30$; each score is 0–100. Edge cases: if $n=0$, print only "avg: 0.0".
Based on the task requirements, which condition will correctly exit the input-reading loop?
int i = 0;
// read n scores into scores[]
while (/* condition */) {
scores<u>i</u> = in.nextInt();
i++;
}
i < n
i != n - 1
i > n
i <= n
Explanation
This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on loop condition design within Java coding tasks. The while loop needs to continue reading scores as long as we haven't read all n scores, which means the condition should allow the loop to run while i is less than n. In this scenario, the task requires correctly setting loop bounds to read exactly n scores into the array, where i starts at 0 and increments after each read. Choice B (i < n) is correct because it properly implements the loop to run n times (from i=0 to i=n-1), ensuring all n scores are read into the array. This demonstrates understanding of zero-based indexing and proper loop termination. Choice A (i <= n) is incorrect due to an off-by-one error, which would attempt to read n+1 scores and cause an array index out of bounds exception. To help students: Emphasize the relationship between array indices (0 to n-1) and loop counters, and practice tracing loops with small values of n. Encourage students to verify loop bounds by checking the first and last iterations.
You are implementing linear search for a school inventory app. The program reads a sorted array of $n$ integers (IDs) and then searches for a target ID using linear search from left to right. It must use iteration and selection: if the current element equals the target, return its index; else continue. Input: first line $n$, second line $n$ integers, third line target. Output: the index if found, otherwise -1. Constraints: $0 \le n \le 100$; IDs are 0–9999.
Given the task requirements, which of the following correctly implements the required loop structure?
int index = -1;
for (int i = 0; i < arr.length; i++) {
// check here
}
System.out.println(index);
if (arr[i] != target) { index = i; break; }
if (arr[i] = target) { index = i; break; }
if (arr[i] == target) { index = i; }
if (arr[i] == target) { index = i; break; }
Explanation
This question tests AP Computer Science A skills in implementing selection and iteration algorithms, specifically focusing on linear search implementation with early termination within Java coding tasks. Linear search requires checking each element sequentially until the target is found, at which point the search should stop immediately to avoid overwriting the found index with later non-matching elements. In this scenario, the task requires finding the first occurrence of the target and returning its index, which necessitates both setting the index and breaking out of the loop. Choice B is correct because it properly implements the search by checking equality (arr[i] == target), storing the index (index = i), and immediately exiting the loop (break) to preserve the first found index. Choice A is incorrect because without the break statement, the loop continues and index would be overwritten if the target appears multiple times, returning the last occurrence instead of the first. To help students: Demonstrate the difference between finding first versus last occurrence, and emphasize the role of break in controlling loop flow. Practice tracing searches with arrays containing duplicate values to understand why early termination matters.