AP Computer Science A • Unit 4.14

Searching Algorithms

Detailed answer explanations for the Unit 4.14 multiple-choice practice questions.

Q1C
Q2B
Q3A
Q4C
Q5C
Q6C
Q7A
Q8C
Q9B
Q10B
Q11C
Q12C
Q13C
How to use this page: First try each question without looking at the explanation. Then compare your answer with the key and read why the other choices are not correct.

Answer Explanations

Q1

What does a linear search do?

AChecks only the first element
BRequires the data to be sorted
CChecks values in order until the target is found or the data ends
DChecks only the middle element
Correct answer: C. A linear search examines one value at a time and stops when it finds the target or after it has checked every possible position.
Explanation

Searching answers two closely related questions: does the target exist, and where is it? The sequential pattern answers both by walking the collection in order, and the same pattern works with arrays, ArrayLists, and the rows of a 2D array.

  • A is not correct: Checking only the first element would report failure for every target stored anywhere after index 0, so the traversal would never reach most of the data.
  • B is not correct: Linear search checks elements in sequence until it finds the target or reaches the end, so sorted data is not required for it to work.
  • D is not correct: Looking only at the middle element leaves every other position unexamined, and it is not the one-value-at-a-time traversal that defines a sequential search.
Q2

Which approach returns the last occurrence of a target?

ASearch from the front and stop at the first match
BSearch from the end and stop at the first match
CReturn the collection's length
DStop after checking the middle value
Correct answer: B. Starting at the end and moving toward index 0 means the first match reached is the last one in the collection.
Explanation

Direction chooses which occurrence is reported. Searching from left to right returns the first occurrence, and searching from right to left returns the last. Either direction is a valid linear search when its returned match agrees with the method's specification.

  • A is not correct: Stopping at the first match found from the front reports the first occurrence, which is the earliest index, not the last one.
  • C is not correct: The collection's length is a count of elements, not a position where the target was seen, so it says nothing about where any match is.
  • D is not correct: Stopping at the middle value ends the search before the remaining positions are checked, so a later match is never reached at all.
Q3

What does an index search commonly return when the target is absent?

A-1
B0
CThe target value
DThe final valid index
Correct answer: A. When the traversal ends without a match, an index search returns a special not-found value, and -1 is the usual choice.
Explanation

This kind of special result is called a sentinel value. It has to be a result that no successful search could produce, and since valid indexes start at 0 and count upward, -1 can never be mistaken for a real position.

  • B is not correct: 0 is a valid index, so returning it would be indistinguishable from a real match found at the very first position.
  • C is not correct: Returning the target value gives back what the caller already supplied, and it does not report whether or where the value was located.
  • D is not correct: The final valid index is a real position in the collection, so a caller would read it as a successful match at the last element.
Q4

Which pair adapts array search to an ArrayList?

Alength and a[i]
Blength() and charAt(i)
Csize() and get(i)
Drows() and cols()
Correct answer: C. An ArrayList uses the same search pattern, but size() replaces length and get(i) replaces array[i].
Explanation

Only the operations that count elements and read one element change. The loop, the success condition, the returned index, and the -1 after the loop all stay the same, which is why the two versions of find look so much alike.

  • A is not correct: length and a[i] are the array operations themselves, so this pair is what is being replaced rather than the replacement.
  • B is not correct: These are the operations the section does not use for a list traversal, and neither one counts the elements of an ArrayList or reads the value stored at index i.
  • D is not correct: Neither of these names appears in the section's list search, and a one-dimensional ArrayList search does not deal in rows and columns.
Q5

Which expression compares the contents of two String objects?

Aa == b
Ba.length == b.length
Ca.equals(b)
Da.get(b)
Correct answer: C. equals compares the contents of two String objects, which is what a text search needs to decide.
Explanation

== checks whether two references refer to the same object, not whether they contain the same characters. That is why "hi" == s can be false while "hi".equals(s) is true when s was built with new String("hi").

  • A is not correct: This compares references and asks whether both names refer to the same object, so matching text stored in two separate objects can be missed.
  • B is not correct: Two different strings can hold the same number of characters, so agreeing on a count says nothing about whether the characters themselves match.
  • D is not correct: get is the ArrayList operation that reads the element at an index, and it is not how the contents of two strings are compared.
Q6

Which statement about linear search is true?

AIt checks only sorted collections.
BIt always checks every value.
CIt can search unsorted collections.
DIt must begin at index 0.
Correct answer: C. Linear search checks elements in sequence until it finds the target or reaches the end, so sorted data is not required.
Explanation

The algorithm makes no assumption about order. It simply examines one value at a time, and it stops as soon as a match settles the answer or after every position has failed.

  • A is not correct: Sorted order is not a requirement of the algorithm, and a sequential pass works just as correctly on values that are stored in no particular order.
  • B is not correct: If the first value matches, the search makes one element comparison and returns immediately, so the whole collection is not always examined.
  • D is not correct: A search may begin at either end, and findLast starts at values.length - 1 and counts down to find the last occurrence.
Q7

Consider the following code segment. What is the final value of result?

int[] data = {7, 4, 7, 2};
int result = -1;
for (int i = 0; i < data.length; i++) {
    if (data[i] == 7) {
        result = i;
        break;
    }
}
A0
B1
C2
D-1
Correct answer: A. The first element checked is 7, so the match happens at index 0 and break ends the loop right there.
Explanation

The loop begins at index 0 and moves forward, so it reports the first occurrence. A match settles the answer immediately, which is the best case for a linear search: one element comparison.

  • B is not correct: Index 1 holds 4, and the loop never reaches it because the break has already stopped the traversal at the earlier match.
  • C is not correct: Index 2 holds the later 7, but a front-to-back search that stops at the first match reports the first occurrence, not this one.
  • D is not correct: -1 is the starting value that would survive only if no element matched, and here the very first element does match.
Q8

Consider the following method call. What is the final value of result?

int[] v = {5, 1, 5, 8};
int result = -1;
for (int i = v.length - 1; i >= 0; i--) {
    if (v[i] == 5) {
        result = i;
        break;
    }
}
A0
B1
C2
D-1
Correct answer: C. The loop starts at the last index and counts down, so it reaches the 5 at index 2 before the one at index 0.
Explanation

To find the last occurrence, start at the end. The first match reached going right to left is the last one in the collection, which is exactly the pattern findLast uses with i = values.length - 1 and i >= 0.

  • A is not correct: Index 0 also holds 5, but the countdown reaches the later match first and break stops the loop before index 0 is examined.
  • B is not correct: Index 1 holds 1, which is not the target, so the comparison there fails and result is not changed.
  • D is not correct: -1 would remain only if no value matched, and this array contains the target twice.
Q9

Consider the following method. What does has(new int[] {4, 2}, 2) return?

public static boolean has(int[] a, int t) {
    for (int value : a) {
        if (value == t) {
            return true;
        }
        return false;
    }
    return false;
}
Atrue
Bfalse
C2
D-1
Correct answer: B. This is the early-return bug: the first value is 4, which is not the target, so false is returned before the second element is ever checked.
Explanation

The success return belongs inside the loop because a match settles the answer, but the failure return belongs after the loop because every value must fail first. Returning false inside the loop after the first non-match stops the search too soon.

  • A is not correct: true would require the loop to reach the 2 stored in the second position, but the method has already returned on its first pass.
  • C is not correct: The method's return type is boolean, so it reports whether the target exists rather than handing back the target value itself.
  • D is not correct: -1 is the not-found value used by an index search, and this method returns a Boolean result instead of a position.
Q10

Consider the following code segment. Assume n stores [6, 3, 8, 3]. What is the final value of i?

int i = 0;
while (i < n.size() && n.get(i) != 8) {
    i++;
}
A1
B2
C3
D-1
Correct answer: B. The loop advances past 6 and 3 and stops when n.get(i) is 8, which happens at index 2.
Explanation

This is the same sequential pattern written with a while loop: it keeps moving forward while the position is valid and the value is not the target. The condition i < n.size() also guards against running past the end when the target is absent.

  • A is not correct: At index 1 the list holds 3, which is not the target, so the condition is still true and i is incremented again.
  • C is not correct: Index 3 is never reached, because the loop condition becomes false as soon as the value at index 2 equals the target.
  • D is not correct: i starts at 0 and only ever increases, so it cannot become negative, and here the target is present anyway.
Q11

Consider a row-by-row search of this array. The search stops when it finds 4. How many element comparisons are made?

int[][] grid = {{2, 5, 1}, {7, 4, 9}};
A2
B4
C5
D6
Correct answer: C. A row-by-row traversal checks the three values of the first row, then 7 and 4 in the second row, which is five element comparisons before it stops.
Explanation

A 2D linear search uses a row-major traversal: choose a row, then search its columns. The number of values checked depends on where the target appears, and the search returns immediately once a match is found.

  • A is not correct: Two comparisons would only cover part of the first row, and the target does not appear there at all.
  • B is not correct: Four comparisons would stop partway through, at the first value of the second row, before the target has been reached.
  • D is not correct: Six is the full count of elements in this array, but the search returns as soon as it finds the target and does not check the value after it.
Q12

A method searches every row of g. Which condition completes the outer loop header?

for (int r = 0; __________; r++) {
    for (int c = 0; c < g[0].length; c++) {
        // compare g[r][c] with target
    }
}
Ar < g[0].length
Br <= g.length
Cr < g.length
Dr < g.length - 1
Correct answer: C. g.length is the number of rows, so this condition lets r take each valid row index and stops after the last one.
Explanation

For an array, use i < a.length. The row loop and the column loop count different things: the outer loop chooses a row with g.length, and the inner loop walks that row with g[0].length.

  • A is not correct: This bounds the row index by the column count, a different number whenever the array is not square, so rows can be skipped or overrun.
  • B is not correct: Using <= eventually asks for an invalid index, since the last valid row index is one less than g.length.
  • D is not correct: Stopping one row early leaves the final row unsearched, so a method that is supposed to search every row would miss any target stored there.
Q13

An array contains six values. A linear search begins at index 0, and the target is absent. How many element comparisons are made?

A1
B3
C6
D7
Correct answer: C. When the target is missing, every position must fail before the method can report not found, so all six elements are compared.
Explanation

Best case is one comparison and worst case checks all n elements. If the target is missing or is the last value checked, a collection of n elements requires n comparisons.

  • A is not correct: One comparison is the best case, which happens only when the very first value checked is the target.
  • B is not correct: Stopping after three comparisons would leave half the array unexamined, and a later value might still have matched.
  • D is not correct: There are only six elements to compare, so there is no seventh position for the search to check.