01 / 21

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.

Java Algorithms

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.

Target
The value you are looking for inside the array.
Index
The position where the target is found, starting at \( 0 \).
Not Found
Return \( -1 \) when the target does not exist in the array.

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.

14 27 3 42 9 51 0 1 2 3 4 5 scanning left to right ✓ Found at index 3

Why Does It Matter?

Simple
Easiest algorithm to implement and understand: just one loop.
Universal
Works on any array: sorted or unsorted, numbers or objects.
Foundation
Understanding it unlocks binary search, hash tables, and more.

The Algorithm

1
Start at index \( i = 0 \).
2
Compare the element at index \( i \) with the target value.
3
If they match, return \( i \).
4
Otherwise, increment \( i \) and repeat step 2.
5
If \( i \) exceeds the last index, return \( -1 \) (not found).

Flowchart of Linear Search

Start: \( i = 0 \)
\( i < \text{length}? \)
No
return \( -1 \)
Yes
\( \text{arr}[i] == \text{target}? \)
Yes
return \( i \)
No
\( i = i + 1 \)

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

1
Identify the collection: Is it an int[], String[], or ArrayList?
2
Determine the comparison: Use == for primitives, .equals() for objects.
3
Write the loop: Iterate from index \( 0 \) to \( \text{length} - 1 \).
4
Return early on match: Exit the method as soon as the target is found.
5
Handle not-found: Return \( -1 \) (or false) after the loop ends.

Example 1: Integer Array

5 12 8 3 20 7 1 0 1 2 3 4 5 6 ✕ ✕ ✕ ✕ ✓ target = 20

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

10 25 33 4 18 7 ✕ ✕ ✕ ✕ ✕ ✕ target = 99 Not found: return -1

Time Complexity: \( O(n) \)

Best Case
\( O(1) \): target is the first element.
Average Case
\( O(n/2) \approx O(n) \): target is roughly in the middle.
Worst Case
\( O(n) \): target is last or absent.

Common Mistakes

✕ Using \( == \) for Strings
The \( == \) operator compares object references, not content. Always use \( .\text{equals}() \) for String comparisons.
✕ Off-by-One Error
Using \( i \le \text{arr.length} \) causes an ArrayIndexOutOfBoundsException. The condition must be \( i < \text{arr.length} \).
✕ Not Returning -1
Forgetting the return \( -1 \) after the loop means the method won't compile (missing return statement).

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

The code above contains a bug. What is it?