Linear Search AP CSA

Linear Search in AP CSA: Complete Guide (2025-2026)

Linear search is the go-to algorithm for finding a value in an unsorted array or ArrayList. It is Unit 4 content (Data Collections, 30–40% of the exam) and appears in both MCQ trace questions and FRQ method-writing. Master first-match, last-match, and count variants—and never confuse returning the value vs. the index.

How Linear Search Works

Iterate from index 0 to arr.length - 1. For each element, check if it matches the target. Return the index (or value, or boolean) on a match. Return a sentinel (-1 or false) after the loop if no match was found.

Runtime: O(n) worst case. Works on unsorted data—making it the default AP CSA search algorithm since sorted arrays are rarely guaranteed.

Search Variants

  • First-match: return i immediately inside loop; return -1 after
  • Last-match: update a variable on every match; return it after loop
  • Count: increment counter on every match; return after loop
  • Boolean exists: return true on first match; return false after loop

Code Examples

Example 1: First-Match Linear Search

What does search(arr, 7) return for arr = {4, 7, 2, 7}?
public class Search {
    public static int firstMatch(int[] arr, int target) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == target) {
                return i;
            }
        }
        return -1;
    }
    public static void main(String[] args) {
        int[] arr = {4, 7, 2, 7};
        System.out.println(firstMatch(arr, 7));   // first 7
        System.out.println(firstMatch(arr, 99));  // not found
    }
}

Example 2: Count and Last-Match

How many times does 5 appear, and what is its last index?
public class MultiSearch {
    public static int countOf(int[] arr, int t) {
        int count = 0;
        for (int v : arr) if (v == t) count++;
        return count;
    }
    public static int lastMatch(int[] arr, int t) {
        int lastIdx = -1;
        for (int i = 0; i < arr.length; i++)
            if (arr[i] == t) {
                lastIdx = i;
            }
        return lastIdx;
    }
    public static void main(String[] args) {
        int[] data = {5, 3, 5, 9, 5};
        System.out.println("Count: " + countOf(data, 5));
        System.out.println("Last idx: " + lastMatch(data, 5));
    }
}

Example 3: String Array Search

Does .equals() correctly identify matching Strings?
public class WordSearch {
    public static boolean contains(String[] words, String target) {
        for (String w : words) {
            if (w.equals(target)) {
                return true;
            }
        }
        return false;
    }
    public static void main(String[] args) {
        String[] vocab = {"alpha", "beta", "gamma"};
        System.out.println(contains(vocab, "beta"));
        System.out.println(contains(vocab, "delta"));
    }
}

Common Pitfalls

1. Returning the Value Instead of the Index

Returning arr[i] instead of i is the single most common linear search error. Re-read the method contract before writing.

2. Using == for String Comparison

Always use .equals() when searching String arrays. == compares references and gives false even for identical content.

3. First-Match vs Last-Match Pattern

First-match: return i INSIDE the loop. Last-match: update a variable inside the loop, return it AFTER.

4. ArrayList Off-by-One

Use i < list.size(), never i <= list.size(). Last valid index is size() - 1.

AP Exam Tip: FRQ parts saying "find the first occurrence" vs "find the last occurrence" need different patterns. Circle the word and code the pattern deliberately.
âš  Watch Out: A backward loop returning on first match gives the last forward occurrence. The MCQ tests this distinction.

Check for Understanding

Score: 0 / 0 answered (8 total)
1. A linear search method should return an index. IDENTIFY the bug.
public static int search(int[] arr, int target) {{
    for (int i = 0; i < arr.length; i++) {{
        if (arr[i] == target) {
            return arr[i];
        }
    }}
    return -1;
}}
2. Three patterns for finding the last index where target appears. WHICH are correct?

I. int idx=-1; for(int i=0;i
II. for(int i=a.length-1;i>=0;i--) if(a[i]==t) return i; return -1;
III. for(int i=0;i
3. What is returned by search({{5,3,5,8}}, 5)? PREDICT.
public static int search(int[] a, int t) {{
    for (int i = 0; i < a.length; i++)
        if (a[i] == t) {
            return i;
        }
    return -1;
}}
4. Linear search on an array of length n. WHICH describes its worst-case comparison count?
5. Searching a String array for a target. WHICH conditions correctly identify a match?

I. if (words[i] == target)
II. if (words[i].equals(target))
III. if (words[i].compareTo(target) == 0)
6. What does firstNegative({{4,-2,7,-1,3}}) return? PREDICT.
public static int firstNegative(int[] arr) {{
    for (int i = arr.length - 1; i >= 0; i--) {{
        if (arr[i] < 0) {
            return i;
        }
    }}
    return -1;
}}
7. WHICH scenario requires linear search rather than direct access?
8. Bug hunt on an ArrayList search. WHICH line is wrong?
1: public static int findWord(ArrayList words, String w) {{
2:   for (int i = 0; i <= words.size(); i++) {{
3:     if (words.get(i).equals(w)) return i;
4:   }}
5:   return -1;
6: }}

Frequently Asked Questions

Linear search works on unsorted data. Binary search requires a sorted array and runs in O(log n). AP CSA FRQs almost always use linear search because sorted arrays are rarely guaranteed.

Yes. Replace arr[i] with list.get(i) and arr.length with list.size(). Use i < list.size() as the loop condition.

For index searches: -1. For boolean searches: false. For count: 0 (or the count, which might be 0). The FRQ spec always tells you which.

No. Enhanced for loops give you the value, not the index. Use a standard indexed for loop when you need to return the position.

An empty array causes the loop body to never execute, so the method correctly returns -1 or false. No AIOOB occurs because arr.length = 0 makes 0 < 0 false immediately.

1-on-1 Expert Support

Array search and traversal are the backbone of the AP CSA FRQ. Work with an expert whose students score 5s at twice the national rate.

View Tutoring Options

Related Topics

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]