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.
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.
| Search | Loop | Result |
|---|---|---|
| First index of a value | Forward from 0 | Index of the first match, or −1 |
| Last index of a value | Backward from length − 1 | Index of the last match, or −1 |
| Is the value present? | Either direction | true at the first match; false after the loop |
| First element with a property | Forward, testing a condition | Its index, or −1 |
| Value in a 2D array | Each row, then a 1D search of that row | Row (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.
| i | a[i] | a[i] == 27? | Action |
|---|---|---|---|
| 0 | 14 | false | continue |
| 1 | 3 | false | continue |
| 2 | 27 | true | return 2 |
| 3, 4 | — | — | never checked |
The Standard Linear Search
Predict the output.
public static int linearSearch(int[] a, int target)
{
for (int i = 0; i < a.length; i++)
{
if (a[i] == target)
{
return i;
}
}
return -1;
}
2
0
-1
- 1Check in order. The loop compares each element with the target, starting at index 0.
- 2Stop when found.
return iends the method at the first match: 27 is first found at index 2. - 3Absent. 5 matches nothing, so the loop finishes and the method returns −1.
Giving Up After One Element
This version returns −1 too early. Predict the output.
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;
}
-1
0
- 1Both branches return, so the loop body runs only once: only
a[0]is ever checked. - 227 is reported missing even though it is in the array; 14 is found only because it is first.
- 3The fix: remove the
else; return −1 only after 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.
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.
Finding the Last Occurrence
Search backward to find the last index of a value.
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;
}
4
1
- 1Start at
a.length - 1, the last valid index, and move toward 0. - 2The first match found is the last occurrence: index 4 for 27, after one check.
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.
Searching With equals
Predict the output.
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;
}
2
-1
- 1
get(i)andsize()replacea[i]anda.length. - 2
equalscompares text, so "Quarry" is found at index 2. - 3Case matters: "quarry" does not equal "Quarry", so the search returns −1.
equals.The First Value Above a Limit
A search can look for the first element with a property, not just an exact value.
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;
}
2
-1
- 1The condition replaces
==: the first element greater than 30 is 31, at index 2. - 2No element exceeds 40, so the result is −1.
Searching by an Attribute
Search an array of objects using accessor methods.
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;
}
}
2
Glasshouse
- 1A
whileloop form. The loop continues while elements remain and the current one is not a match. - 2Short-circuit
&&. Whenireaches the length, the bounds check fails first, sosongs[i]is never evaluated out of range. - 3After the loop, an index less than the length means a match: "Northbound" at 2, and the first song over 240 seconds is "Glasshouse".
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.
Search Each Row in Turn
A 1D search is applied to each row (Figure 3).
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;
}
row 1, column 2
-1
- 1Access each row:
g[r]is a 1D array. - 2Apply a linear search to that row with
indexIn. Row 0 has no 8; row 1 has 8 at column 2, sofindRowreturns 1. - 3Not found anywhere: after every row is searched, the result is −1.
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.
| Situation | Elements checked (n elements) |
|---|---|
| Target is the first element checked | 1 (best case) |
| Target at the k-th position checked | k |
| Target is the last element checked | n |
| Target is not present | n (always the worst case) |
Best Case and Worst Case
Count how many elements are checked before the search ends.
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;
}
1
3
5
- 1Best case. 14 is first: 1 check.
- 2Middle. 27 is first found at index 2: 3 checks.
- 3Worst case. 5 is absent: all 5 elements are checked.
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.
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.