Linear Search
in Java
Learn how to sequentially scan through arrays and lists to find a target value: the simplest and most fundamental search algorithm in computer science.
What Is Searching?
Searching is the process of locating a specific element within a collection of data. In Java, that collection is typically an array or an ArrayList.
What Is Linear Search?
Linear search (also called sequential search) checks each element in the array one by one, from the first element to the last, until it finds the target or reaches the end.
Why Does It Matter?
The Algorithm
Flowchart of Linear Search
Java Implementation
public static int linearSearch(int[] arr, int target) { for (int i = 0; i < arr.length; i++) { if (arr[i] == target) { return i; // found: return index } } return -1; // not found }
Linear Search vs Binary Search
| Linear Search | Binary Search | |
|---|---|---|
| Requires sorting? | No | Yes |
| Time complexity | \( O(n) \) | \( O(\log n) \) |
| Best case | \( O(1) \) | \( O(1) \) |
| Implementation | Simple loop | Divide and conquer |
| Works on objects? | Yes (.equals) | Only if Comparable |
How to Apply Linear Search
Example 1: Integer Array
Example 2: String Array
public static int linearSearch(String[] arr, String target) { for (int i = 0; i < arr.length; i++) { if (arr[i].equals(target)) { return i; } } return -1; }
Given {"cat", "dog", "bird", "fish"} and target "bird", the method checks indices 0, 1, then finds a match at index 2.
Example 3: ArrayList
public static int linearSearch(ArrayList<Integer> list, int target) { for (int i = 0; i < list.size(); i++) { if (list.get(i) == target) { return i; } } return -1; }
Example 4: Target Not Found
Time Complexity: \( O(n) \)
Common Mistakes
Summary at a Glance
| Property | Detail |
|---|---|
| Algorithm type | Sequential / Brute-force |
| Data requirement | None (works on unsorted data) |
| Best-case time | \( O(1) \) |
| Worst-case time | \( O(n) \) |
| Space complexity | \( O(1) \) |
| Return value (found) | Index of target |
| Return value (not found) | \( -1 \) |
| Comparison (primitives) | \( == \) |
| Comparison (objects) | \( .\text{equals}() \) |
Question 1 of 5
What does linear search return when the target is not found in the array?
Question 2 of 5
Given int[] arr = {4, 9, 2, 7, 5}, what does \( \text{linearSearch(arr, 7)} \) return?
Question 3 of 5
When searching an array of String objects, which comparison should be used inside the loop?
Question 4 of 5
What is the worst-case time complexity of linear search on an array of \( n \) elements?
Question 5 of 5
public static int linearSearch(int[] arr, int target) {
for (int i = 0; i <= arr.length; i++) {
if (arr[i] == target) {
return i;
}
}
return -1;
}
The code above contains a bug. What is it?