Sorting puts data in order. Searching answers the other everyday question: is this value in the array, and if so, where?
Finding a roll number in the attendance list, checking whether a username is taken, looking up a product by its code: all of these are searches.
We'll start with the simplest search there is.
By the end of this lesson, you will understand:
- How Linear Search works
- How to trace it by hand
- How to write it in code
- Its Big-O, and when it is the right choice
What Is Linear Search?
Linear Search checks the values one at a time, from the start of the array:
- Look at the first value. Is it the target, the value you're looking for?
- If yes, you're done. Return its index.
- If not, move to the next value and repeat.
- If you reach the end without finding it, the target is not in the array. Return
-1.
Why -1? Every real index is 0 or more, so -1 can never be mistaken for a position. It is the usual way to say "not found".
Watch it below. The value being checked is lifted in amber, values already checked are crossed out, and the target turns green when it is found. Then try Missing value to see what happens when the target isn't there.
The Lost Keys Analogy
You've lost your keys somewhere in your bag, which has six pockets.
1. Start With the First Pocket
Check the first pocket. No keys? Move on.
2. Check Each Pocket in Turn
Keep going, one pocket at a time. You can't skip any, because the keys could be in any of them.
3. Stop When You Find Them
The moment you find the keys, you stop. There's no need to check the remaining pockets.
4. Or Reach the End
If you've checked every pocket and found nothing, you know for certain: the keys are not in the bag.
Tracing It by Hand
Let's search [7, 3, 9, 1, 5, 8] for 5.
i | a[i] | Is it 5? |
|---|---|---|
| 0 | 7 | No, move on |
| 1 | 3 | No, move on |
| 2 | 9 | No, move on |
| 3 | 1 | No, move on |
| 4 | 5 | Yes, return 4 |
Found at index 4, after 5 checks. The last value, 8, is never looked at.
Now search the same array for 6. Every check says "No", all 6 values are checked, and the search returns -1. A missing value is the worst case: the only way to be sure something isn't there is to look everywhere.
Linear Search in Code
public class Main {
static int linearSearch(int[] a, int target) {
for (int i = 0; i < a.length; i++) {
if (a[i] == target) {
return i; // found it: return its index
}
}
return -1; // checked every value: not there
}
public static void main(String[] args) {
int[] marks = {7, 3, 9, 1, 5, 8};
System.out.println(linearSearch(marks, 5)); // 4
System.out.println(linearSearch(marks, 6)); // -1
}
}Let's connect the code to the trace:
- The loop visits
i = 0, 1, 2, ..., one row of the trace table per step. return ileaves the function immediately, which is the "stop when you find it" step.return -1sits after the loop, so it only runs once every value has been checked.
Built-in Versions
You will rarely write Linear Search yourself in real code. Most languages have it built in:
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> marks = List.of(7, 3, 9, 1, 5, 8);
System.out.println(marks.indexOf(5)); // 4
System.out.println(marks.indexOf(6)); // -1
System.out.println(marks.contains(6)); // false
}
}All of these check the values one by one, so they are Linear Search under the hood, with the same speed.
How Fast Is Linear Search?
| Case | Example | Time | Why |
|---|---|---|---|
| Best | The target is first | O(1) | One check and done |
| Average | The target is somewhere in the middle | O(n) | About n / 2 checks |
| Worst | The target is last, or missing | O(n) | Every value is checked |
| Extra memory | Any | O(1) | Just the loop variable |
O(n) means the work grows in step with the data. Search 10 values and you might check 10. Search a list of 10 lakh (1,000,000) customers and you might check all 10 lakh.
Common Mistakes
1. Returning -1 Inside the Loop
for each i:
if a[i] == target: return i
else: return -1 // wrong!
This gives up after checking just the first value. "Not found" can only be decided after the loop has checked everything, so return -1 belongs after the loop.
2. Going One Step Too Far
Writing i <= a.length instead of i < a.length reads one place past the end of the array. Java stops with an error, and in C it is undefined behaviour.
3. Using 0 to Mean "Not Found"
0 is a real index: the first value. If the target is first and your function returns 0 for "not found" too, the two cases look the same. That's why -1 is used.
When Should You Use Linear Search?
Good for:
- Unsorted data: it is the only option that doesn't need the data in order
- Small arrays, where checking everything is quick anyway
- Searching just once: sorting first costs
O(n log n), which is more than a singleO(n)search
Not good for:
- Searching a large array again and again. If the data is sorted, there is a dramatically faster way.
In the next lesson, we will learn that faster way: Binary Search, which finds a value among a million sorted values in at most 20 checks.
Remember This
If you remember only one thing from this lesson, remember: Linear Search checks values one by one until it finds the target, or returns -1 after checking them all. It works on any array, sorted or not, and takes O(n) time.