Sequential search practice problem 2

Sequential search is an algorithm in which a data structure, such as an array or a list, not known to be sorted is searched element by element from beginning to end for a specific value.

On the AP Computer Science Exam, you must recognize the algorithm when it is presented in code. You should also be able to recognize a variation of the algorithm, such as a search from the end to the beginning. You may be expected to compare the efficiency of sequential search to (the much more efficient) binary search.

Assignment

Method sequentialSearch is to returns the index of key in x or -1 if key is not in x.

Complete method sequentialSearch below.

public static int sequentialSearch(int[] x, int key)

See the Sequential search practice problem solution or review it with AP CS Tutor Brandon Horn.

Get AP CS Help

2 thoughts on “Sequential search practice problem

  1. Reply Taylor Jan 25,2012 8:10 pm

    public static int sequentialSearch(int[] x, int key)
    {
    for (int i = 0; i < x.length; i++)
    if (x[i] == key)
    return i;

    return -1;
    }

    • Reply Brandon Horn Jan 25,2012 8:34 pm

      Yes, this works. It’s identically to the solution presented on the site. You can also write this recursively if you’d like.

Leave a Reply