AP Computer Science A · Study guide

Linear Search Algorithms

AP® Computer Science A · Data Collections

Linear Search Algorithms

Finding specific information in a collection by checking each element in order: returning an index or −1, searching from either end, searching ArrayLists, objects, and 2D arrays, and counting how many elements a search checks.

Big Picture

Linear search algorithms are standard algorithms that check each element in order until the desired value is found or all elements in the array or ArrayList have been checked. A linear search can begin from either end of the collection. The usual result is the index of the match, with −1 meaning "not found". When applied to a 2D array, each row is accessed and a linear search is applied to each row.

1Checking Each Element in Order

A linear search answers the question "where, if anywhere, is this value?" by looking at the elements one at a time. It starts at one end, compares the current element with the value being sought, and moves to the next element if they differ. The search ends as soon as a match is found, or when there are no elements left to check.

Linear search works on any collection, sorted or not, because it makes no assumptions about where a value might be. That generality has a cost: in the worst case, every element is examined. The algorithm is the same for arrays and ArrayList objects, with get(i) and size() replacing a[i] and a.length.

SearchLoopResult
First index of a valueForward from 0Index of the first match, or −1
Last index of a valueBackward from length − 1Index of the last match, or −1
Is the value present?Either directiontrue at the first match; false after the loop
First element with a propertyForward, testing a conditionIts index, or −1
Value in a 2D arrayEach row, then a 1D search of that rowRow (and column), or −1

2Returning the Index, or −1

The standard linear search is a method that returns the index of the first element equal to the target. Inside the loop, a return statement ends the method the moment a match is found, so no further elements are checked. If the loop finishes, every element has been checked without a match, and the method returns −1, a value that can never be a valid index.

The caller tests the result: a value of −1 means the target is absent, and any other value is a position that can be used with the collection. Returning a boolean instead answers only whether the value is present; returning the index answers both questions at once.

Tracing a search means recording, for each index checked, the element there and whether it matches, as in the trace below. The trace ends at the first match; the elements after it are never examined, which is why the method returns the index of the first occurrence when a value appears more than once.

ia[i]a[i] == 27?Action
014falsecontinue
13falsecontinue
227truereturn 2
3, 4——never checked
Worked Example 1 Index or -1

The Standard Linear Search

Predict the output.

Code
public static int linearSearch(int[] a, int target)
{
    for (int i = 0; i < a.length; i++)
    {
        if (a[i] == target)
        {
            return i;
        }
    }
    return -1;
}
Output
2
0
-1
  1. 1Check in order. The loop compares each element with the target, starting at index 0.
  2. 2Stop when found. return i ends the method at the first match: 27 is first found at index 2.
  3. 3Absent. 5 matches nothing, so the loop finishes and the method returns −1.
Result: The output is 2, 0, and -1. A linear search returns the index of the first match, or −1 after checking every element without a match.
Worked Example 2 A common bug

Giving Up After One Element

This version returns −1 too early. Predict the output.

Code
public static int brokenSearch(int[] a, int target)
{
    for (int i = 0; i < a.length; i++)
    {
        if (a[i] == target)
        {
            return i;
        }
        else
        {
            return -1;
        }
    }
    return -1;
}
Output
-1
0
  1. 1Both branches return, so the loop body runs only once: only a[0] is ever checked.
  2. 227 is reported missing even though it is in the array; 14 is found only because it is first.
  3. 3The fix: remove the else; return −1 only after the loop.
Result: The output is -1 and 0. "Not found" can be decided only after every element has been checked.
Common Mistake 1 · Returning −1 Inside the Loop

An else return -1; inside the loop ends the search after the first element. "Not found" is only known after the loop has checked every element, so the return -1; belongs after the loop.

Figure 1. A search for a value that is not present checks every element before returning −1, a value that cannot be a valid index.

3Searching From Either End

Linear search algorithms can begin the search process from either end of the array or ArrayList. Searching forward, from index 0, finds the first occurrence of a value. Searching backward, from the last index down to 0, finds the last occurrence, which is useful for questions such as "when was this value most recently recorded?"

A backward search starts at a.length - 1, or list.size() - 1, and continues while the index is at least 0. Starting at the length itself is one past the end and throws an exception on the very first check.

Figure 2. A linear search checks each element in order until the value is found or every element has been checked. It can begin from either end.
Worked Example 3 From the other end

Finding the Last Occurrence

Search backward to find the last index of a value.

Code
public static int lastIndexOf(int[] a, int target)
{
    for (int i = a.length - 1; i >= 0; i--)
    {
        if (a[i] == target)
        {
            return i;
        }
    }
    return -1;
}
Output
4
1
  1. 1Start at a.length - 1, the last valid index, and move toward 0.
  2. 2The first match found is the last occurrence: index 4 for 27, after one check.
Result: The output is 4 and 1. A linear search can begin from either end of the array or ArrayList (Figure 2).
Common Mistake 2 · Starting a Backward Search at the Length

for (int i = a.length; i >= 0; i--) reads a[a.length] first and throws an ArrayIndexOutOfBoundsException. The last valid index is a.length - 1.

4Searching Lists, Strings, and Objects

When the elements are strings, the comparison must use equals, which compares the characters; == asks whether two references refer to the same object and can fail even when the text matches. When the elements are other objects, a search usually compares one attribute, obtained with an accessor method such as getTitle().

A search can also look for the first element that satisfies a condition, such as the first temperature above a limit. The structure is unchanged; only the test inside the loop differs. The same pattern can also be written as a while loop that advances while elements remain and the current one is not a match; short-circuit evaluation of && ensures the bounds check happens before the element is accessed.

Worked Example 4 ArrayList of strings

Searching With equals

Predict the output.

Code
public static int find(ArrayList<String> list, String target)
{
    for (int i = 0; i < list.size(); i++)
    {
        if (list.get(i).equals(target))
        {
            return i;
        }
    }
    return -1;
}
Output
2
-1
  1. 1get(i) and size() replace a[i] and a.length.
  2. 2equals compares text, so "Quarry" is found at index 2.
  3. 3Case matters: "quarry" does not equal "Quarry", so the search returns −1.
Result: The output is 2 and -1. Linear searches of an ArrayList of strings compare elements with equals.
Worked Example 5 Search by condition

The First Value Above a Limit

A search can look for the first element with a property, not just an exact value.

Code
public static int firstAbove(ArrayList<Integer> list, int limit)
{
    for (int i = 0; i < list.size(); i++)
    {
        if (list.get(i) > limit)
        {
            return i;
        }
    }
    return -1;
}
Output
2
-1
  1. 1The condition replaces ==: the first element greater than 30 is 31, at index 2.
  2. 2No element exceeds 40, so the result is −1.
Result: The output is 2 and -1. The same structure finds the first element that satisfies any condition.
Worked Example 6 Objects

Searching by an Attribute

Search an array of objects using accessor methods.

Code
public class Song
{
    private String title;
    private int seconds;

    public Song(String t, int s)
    {
        title = t;
        seconds = s;
    }

    public String getTitle()
    {
        return title;
    }

    public int getSeconds()
    {
        return seconds;
    }
}
Output
2
Glasshouse
  1. 1A while loop form. The loop continues while elements remain and the current one is not a match.
  2. 2Short-circuit &&. When i reaches the length, the bounds check fails first, so songs[i] is never evaluated out of range.
  3. 3After the loop, an index less than the length means a match: "Northbound" at 2, and the first song over 240 seconds is "Glasshouse".
Result: The output is 2 and Glasshouse. Searching objects compares an attribute returned by an accessor method.
Common Mistake 3 · Comparing Strings With ==

Two different String objects with the same characters are not ==. A search that uses == on strings can miss a value that is present. Compare strings with equals.

5Searching a 2D Array

When applying linear search algorithms to 2D arrays, each row must be accessed, then linear search applied to each row of the 2D array. Because each row is a 1D array, the 1D search method can be reused directly: call it on g[0], then g[1], and so on, until a row reports a match or every row has been searched.

The result of a 2D search may be the row where the value was found, its row and column, or simply true. As with a 1D search, "not found" can only be reported after the last row has been searched completely.

Figure 3. To search a 2D array, each row is accessed and a linear search is applied to that row, one row at a time.
Worked Example 7 2D arrays

Search Each Row in Turn

A 1D search is applied to each row (Figure 3).

Code
public static int indexIn(int[] row, int target)
{
    for (int c = 0; c < row.length; c++)
    {
        if (row[c] == target)
        {
            return c;
        }
    }
    return -1;
}

public static int findRow(int[][] g, int target)
{
    for (int r = 0; r < g.length; r++)
    {
        if (indexIn(g[r], target) != -1)
        {
            return r;
        }
    }
    return -1;
}
Output
row 1, column 2
-1
  1. 1Access each row: g[r] is a 1D array.
  2. 2Apply a linear search to that row with indexIn. Row 0 has no 8; row 1 has 8 at column 2, so findRow returns 1.
  3. 3Not found anywhere: after every row is searched, the result is −1.
Result: The output is row 1, column 2, then -1. Applying linear search to a 2D array accesses each row and then searches that row.
Common Mistake 4 · Stopping After the First Row

Returning −1 as soon as one row does not contain the target skips every later row. Move on to the next row instead, and return −1 only after all rows have been searched.

6How Many Elements Are Checked

Determining the results of executing a search includes knowing how much work it does. A linear search checks one element when the target is the first element it examines, and k elements when the target is in the k-th position examined. When the target is the last element examined, or is not in the collection at all, every element is checked.

For a collection of n elements, a search for an absent value always makes n checks, and a search for a present value makes between 1 and n. Doubling the size of the collection roughly doubles the number of checks for an unsuccessful search, which is why linear search becomes slow for very large collections.

Figure 4. The number of elements a linear search checks depends on where the value is: one check when it is first, every element when it is last or absent.
SituationElements checked (n elements)
Target is the first element checked1 (best case)
Target at the k-th position checkedk
Target is the last element checkedn
Target is not presentn (always the worst case)
Worked Example 8 Counting checks

Best Case and Worst Case

Count how many elements are checked before the search ends.

Code
public static int checksToFind(int[] a, int target)
{
    int checks = 0;
    for (int i = 0; i < a.length; i++)
    {
        checks++;
        if (a[i] == target)
        {
            return checks;
        }
    }
    return checks;
}
Output
1
3
5
  1. 1Best case. 14 is first: 1 check.
  2. 2Middle. 27 is first found at index 2: 3 checks.
  3. 3Worst case. 5 is absent: all 5 elements are checked.
Result: The output is 1, 3, and 5. The work a linear search does grows with the position of the target and is greatest when the value is last or absent (Figure 4).

Four Habits for Linear Search

1. Return on a Match

Inside the loop, as soon as it is found.

2. Return −1 After the Loop

Only then is the value known to be absent.

3. Pick the End

Forward for first, backward for last.

4. 2D: Row by Row

Search each row with the 1D search.

Core Synthesis

Linear search algorithms are standard algorithms that check each element in order until the desired value is found or all elements in the array or ArrayList have been checked. Linear search algorithms can begin the search process from either end of the array or ArrayList. When applying linear search algorithms to 2D arrays, each row must be accessed, then linear search applied to each row of the 2D array. A search returns as soon as it finds a match, reports "not found" only after every element has been checked, and checks every element in the worst case.