AP Computer Science A : Searching

Study concepts, example questions & explanations for AP Computer Science A

varsity tutors app store varsity tutors android store

Example Questions

Example Question #24 : Computer Science

Which of the following implements a method named contains for searching an array sequentially, confirming whether or not the array contains a requested element?

Possible Answers:

public int contains(int[] arr, int val) {

      int success = -1;

      for(int i = 0; i < arr.length; i++) {

              if(arr[i] == val) {

                     success = val;

              }

       }

       return success;

}

None of the other answers is correct

public boolean contains(int[] arr, int val) {

       for(int i = 0; i < arr.length; i++) {

              if(arr[i] == val) {

                     return true;

              }

       }

       return false;

}

public boolean contains(int[] arr, int val) {

       for(int i = 0; i < arr.length; i++) {

              if(arr[i] != val) {

                     return false;

              }

       }

       return true;

}

public boolean contains(int[] arr, int val) {

       boolean success;

       for(int i = 0; i <= arr.length; i++) {

              if(arr[i] == val) {

                     success = true;

              } else {

                     success = false;

              }

       }

       return success;

}

Correct answer:

public boolean contains(int[] arr, int val) {

       for(int i = 0; i < arr.length; i++) {

              if(arr[i] == val) {

                     return true;

              }

       }

       return false;

}

Explanation:

The basic way to implement a sequential search is to test each element of an array until you match the value you want to find. All of these possible answers are very close to doing this. They all iterate through the given array. They all do check for the value. However, one option (with the if-else logic) could return false even if the element was found, for it continues to run after it is found. If another value does not match later in the array, the variable success will then be set to false. This will be returned, indicating failure to find the value. The integer-returning method seems to be fine, but it would be ambiguous if the value for the search is negative one. In this one case, this return value will not signal necessarily that it has been found—it could be just the "flag" indicating that nothing was found. Thus, the simplest method is the best here: return true as soon as it is found.

Example Question #1 : Searching

public static int foo(int[] arr, int x) {

    for(int i = 0; i < arr.length; i++) {

        if(arr[i] == x) {

            return i;

        }

    }

    return -1;

}

Given the method defined above, how many times is the word "Indubitably!" output by the code below?

int[] vals = {1,4,51,3,14,91,130,14};

for(int i = 0; i < 20; i++) {

    if(foo(vals,i%4) < 0) {

        System.out.println("Indubitably!");

    }

}

Possible Answers:

5

2

10

None

4

Correct answer:

10

Explanation:

To make this question much easier, first notice that the foo method implements a sequential search.  (This is a search that merely goes through each element of an array and sees if it equals the probe value.)  It returns the index if it is found.  Otherwise, it returns -1.  Now, in the code block in the question itself, the loop iterates for i = 0 to i = 19.  It will only execute a search, however, on the values 0...3.  This is because of the modulus operator.  Thus, it will do (from 0 to 19), 0...3 a total of five times.  Thus, it will probe for 1 and 3 five times—these are each in the array.  So, the word "Indubitably!" will be output a total of ten times.

Example Question #1 : Sequential

True or False. 

 

Sequential search is more efficient than Binary Search.

Possible Answers:

False

True

Correct answer:

False

Explanation:

Sequential search has a running time of O(N). Binary search has a running time of O(log(N)). Because sequential search has to go through each element in a list at least once it's less efficient. 

Example Question #2 : Searching

What is the difference between inorder traversal of a binary search tree and a preorder traversal?

Possible Answers:

Preorder searches through the tree from lowest to highest, inorder does not.

In order traversal processes the left subtree, then the root node, then the right subtree, whereas preorder processes the root node, left subtree, then right subtree.

The only difference is that in order processes the root node, whereas preorder does not.

In order traversal processes the right subtree, then the root node, then the left subtree, whereas preorder processes the left subtree, then the root node, the the right subtree.

They are similar.

Correct answer:

In order traversal processes the left subtree, then the root node, then the right subtree, whereas preorder processes the root node, left subtree, then right subtree.

Explanation:

In this case, the names help to identify the different types of traversals. In order traversal processes the binary tree "in order", meaning it will go through the left subtree, process the node, then go on to the right. Why is this in order? Because remember, a binary sort tree lists any value less than the node to the left, and any value greater to the right, so in order traversal will actually go from greatest to smallest.

Preorder traversal is the same except that it processes the root node first, hence the "pre" order.

Example Question #2 : Searching

public static int foo(int[] arr, int x) {

    int a = 0;

    int b = arr.length - 1;

    while(b >= a) {

        int c = (a + b) / 2;

        int v = arr[c];

        

        if(v == x) {

            return c;

        } else if(v < x) {

            a = c + 1;

        } else {

            b = c - 1;

        }

    }

    return -1;

}

What is the value of y in the code below:

int[] vals = {1,3,4,5,6,31,41,51};

int x = 41;

int y = foo(vals,41);

Possible Answers:

5

-1

41

6

7

Correct answer:

6

Explanation:

The first thing to notice in the code for the method foo is that it implements the algorithm for a binary search.  The value c functions as the midpoint for the algorithm.  This requires that the list be in order.  The values a and b are used to control the loop so as to let you search the correct portions of the list.  If the value in the middle of the list is not equal to what you are looking for (i.e. x), then it looks either "above" or "below" in the list (since it is presumed to be in order).  This is what is happening when either a or is changed.

So, this searches for the value and returns the index number for that value if it is found.  Otherwise, it returns -1.  Since the value 41 is in the array, it returns 6. 

If you do not recognize this algorithm, you are likely to have some problems—and will have to trace the code!!

Example Question #3 : Searching

Which of the following is true for a binary search algorithm?

Possible Answers:

The array being searched must be sorted before searching.

The array needs extra space in order to accomodate swap operations that are part of the search.

The array must be converted into a binary search tree before searching for the value.

The array can be unsorted but will run slower than if it is sorted.

The array must be probed in order from its beginning to its end.

Correct answer:

The array being searched must be sorted before searching.

Explanation:

The binary search presumes that the array being searched is already sorted.  This is because of how it probes the values in the array.  It begins at the center of the array to see if the values match.  If the value is smaller than this center element, it then presumes that the value is in the lower half of the array.  Otherwise, it presumes that the value must be larger and hence in the upper half of the array.  It then probes the center of whichever half it has chosen, continuing to do this until the value has certainly not been found.

Example Question #2 : Searching

What is the difference between inorder traversal of a binary search tree and a preorder traversal?

Possible Answers:

Preorder searches through the tree from lowest to highest, inorder does not.

In order traversal processes the left subtree, then the root node, then the right subtree, whereas preorder processes the root node, left subtree, then right subtree.

The only difference is that in order processes the root node, whereas preorder does not.

In order traversal processes the right subtree, then the root node, then the left subtree, whereas preorder processes the left subtree, then the root node, the the right subtree.

They are similar.

Correct answer:

In order traversal processes the left subtree, then the root node, then the right subtree, whereas preorder processes the root node, left subtree, then right subtree.

Explanation:

In this case, the names help to identify the different types of traversals. In order traversal processes the binary tree "in order", meaning it will go through the left subtree, process the node, then go on to the right. Why is this in order? Because remember, a binary sort tree lists any value less than the node to the left, and any value greater to the right, so in order traversal will actually go from greatest to smallest.

Preorder traversal is the same except that it processes the root node first, hence the "pre" order.

Example Question #2 : Searching

public static int foo(int[] arr, int x) {

    int a = 0;

    int b = arr.length - 1;

    while(b >= a) {

        int c = (a + b) / 2;

        int v = arr[c];

        

        if(v == x) {

            return c;

        } else if(v < x) {

            a = c + 1;

        } else {

            b = c - 1;

        }

    }

    return -1;

}

What is the value of y in the code below:

int[] vals = {1,3,4,5,6,31,41,51};

int x = 41;

int y = foo(vals,41);

Possible Answers:

5

-1

41

6

7

Correct answer:

6

Explanation:

The first thing to notice in the code for the method foo is that it implements the algorithm for a binary search.  The value c functions as the midpoint for the algorithm.  This requires that the list be in order.  The values a and b are used to control the loop so as to let you search the correct portions of the list.  If the value in the middle of the list is not equal to what you are looking for (i.e. x), then it looks either "above" or "below" in the list (since it is presumed to be in order).  This is what is happening when either a or is changed.

So, this searches for the value and returns the index number for that value if it is found.  Otherwise, it returns -1.  Since the value 41 is in the array, it returns 6. 

If you do not recognize this algorithm, you are likely to have some problems—and will have to trace the code!!

Example Question #3 : Searching

Which of the following is true for a binary search algorithm?

Possible Answers:

The array being searched must be sorted before searching.

The array needs extra space in order to accomodate swap operations that are part of the search.

The array must be converted into a binary search tree before searching for the value.

The array can be unsorted but will run slower than if it is sorted.

The array must be probed in order from its beginning to its end.

Correct answer:

The array being searched must be sorted before searching.

Explanation:

The binary search presumes that the array being searched is already sorted.  This is because of how it probes the values in the array.  It begins at the center of the array to see if the values match.  If the value is smaller than this center element, it then presumes that the value is in the lower half of the array.  Otherwise, it presumes that the value must be larger and hence in the upper half of the array.  It then probes the center of whichever half it has chosen, continuing to do this until the value has certainly not been found.

Learning Tools by Varsity Tutors