A girl and a robot thinking together

Think it through · Start with a story

The girl is looking for the card marked 7 in the sequence 4, 7, 2. The robot checks the first card, then the second.

Break Down the Process

Follow the numbered steps, then explain them in your own words
  1. First card4, not the target
  2. Second card7, found it
  3. StopOne match is enough this time

Linear search checks each element one by one and does not require sorting beforehand.

When it finds the target, it can return the position required by the task. If it checks everything without finding a match, it reports that the target is absent.

01What Is Linear Search?

Suppose we have this array:

int a[5] = {7, 3, 9, 2, 6};

To find 9, we can compare it with each element, starting at the first.

7 ✗→3 ✗→9 ✓

02How Do You Write the Code?

int pos = -1;

for (int i = 0; i < n; i++) {
    if (a[i] == target) {
        pos = i;
        break;
    }
}

-1 can mean “not found yet.”

03Why Can You break After Finding It?

If the task asks for any one position containing the target, there is no need to keep checking after finding one.

But if you need to count how many times the target appears, you cannot stop at the first match.

04Does the Data Have to Be Sorted?

No. Linear search also works on unsorted data.

05How Many Checks Can It Take in the Worst Case?

If the target is in the last position, or is not present at all, a sequence of length n requires checking all n elements.

Worst-case work grows in proportion to n → O(n)

06Is Linear Search a Bad Choice?

No. For a small data set, a single search, or unsorted data, linear search is often the simplest and most direct option.

What You Have Learned

  • Linear search compares elements one by one from beginning to end.
  • It does not require sorted data.
  • Whether to stop after finding a match depends on the task.
  • In the worst case it checks n elements, so its complexity is O(n).
  • A simple algorithm may be the right choice for a small task.

Next: Binary Search: Eliminate Half Each Time

Your Turn to Try

How many cards do you need to check to look for 9 among 4, 7, and 2?

Have you decided? Open to see the explanation

All 3 cards. You have to check every one before you can be sure the target is not in the set.