In the first lesson, findMax looked at every number, because the biggest one could be anywhere. Looking for one particular value is similar, except you can stop as soon as you find it. The simplest way to do that is called linear search: check the items one by one from the front, until you find the value or every item has been checked. The result is the index where the value was found, or -1 if it isn't there. It's like looking for a friend's name in a contact list that isn't sorted: you read from the top, one by one. The contact list is the array, and your friend's name is the value you are looking for.
How it works
Look for 9 in an array arr that holds [4, 2, 7, 1, 9, 3, 8, 5]. An index is a position number in the array, starting at 0.
| Step | What is checked | Result |
|---|---|---|
| 1 | arr[0] = 4 |
not 9, keep going |
| 2 | arr[1] = 2 |
not 9, keep going |
| 3 | arr[2] = 7 |
not 9, keep going |
| 4 | arr[3] = 1 |
not 9, keep going |
| 5 | arr[4] = 9 |
found it, return 4 |
Written in JavaScript:
function linearSearch(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) return i; // found it, stop here
}
return -1; // checked them all, not there
}
const numbers = [4, 2, 7, 1, 9, 3, 8, 5];
console.log(linearSearch(numbers, 9)); // 4
console.log(linearSearch(numbers, 6)); // -1
targetis the value you're looking for.- The
forloop runs from index 0 to the last index. arr[i] === targetcompares the item at positioniwith the value you're looking for (===means "is equal to"). As soon as they match,return istops the function right away and returns the index, not the value. Looking for 9 gives 4, because 9 sits at index 4.return -1is written after the loop, so it only runs once every item has been checked and none matched. Why-1? Because no index is ever negative, so-1can't be mistaken for a real index.
How many steps
- Best case: the value you're looking for is at index 0. One check is enough.
- Worst case: the value is at the very end, or not there at all. Every item gets checked. Looking for 6 in the array above takes 8 checks before the answer is
-1.
The amount of data is called n. Because the worst case checks every item, linear search is written O(n): double the data, and the time roughly doubles. For 1,000 items, there are at most 1,000 checks.
When to use linear search
There's a much faster way, binary search (the next lesson), but it only works on data that's already sorted. Sorting the data first takes more steps than one linear search. So linear search is the right choice when:
- the data is not sorted and you only need to search it once,
- the data is small, for example a few dozen items,
- the condition isn't "exactly equal", for example finding the first price under $50.
Arrays in JavaScript have the methods (built-in functions that belong to arrays) arr.indexOf(), arr.includes() and arr.find(). Inside, all three use linear search too. indexOf gives a position, includes only true or false, and find or findIndex search with a condition, such as arr.findIndex((x) => x > 10). One difference: [NaN].indexOf(NaN) gives -1, while [NaN].includes(NaN) gives true.
⚠️ A misplaced return -1, and a loop that's quietly slow
return -1inside the loop. If you writeif (...) return i; else return -1;inside the loop, the function already stops at the first item that doesn't match.return -1goes after the loop.- Forgetting
return -1. Without that line, the function returnsundefined(a sign for "no value") whentargetisn't in the array. The code that uses the result can then give wrong results without anyone noticing. - Linear search inside a loop. A loop that runs 1,000 times, and calls
includes()on a list of 1,000 items each time, can make 1 million checks. If you need to check again and again, put the data in aSetfirst. ASetis a built-in JavaScript container that can answer "is this value here?" without checking its items one by one.
TL;DR: Linear search looks for one value by checking the items of an array one by one from index 0. If it finds that value, it returns its index, not its value. If every item has been checked and the value isn't there, it returns -1, which is written after the loop. The best case is one check and the worst case checks every item, so it is O(n). Use linear search for data that isn't sorted and is searched only once, or for small data. Sorted data that's searched again and again is a better fit for binary search, a much faster way to search that needs sorted data.
⚡ Check one by one from the front
Write:
function linearSearch(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) return i; // found it, stop here
}
return -1; // checked them all, not there
}
const numbers = [4, 2, 7, 1, 9, 3, 8, 5];
console.log(linearSearch(numbers, 9)); // 4
console.log(linearSearch(numbers, 6)); // -1
Meaning: Linear search checks the items of an array one by one from the front. target is the value you're looking for. If it finds target, it returns its index, not its value. If every item has been checked and the value isn't there, it returns -1. The line return -1 is written after the loop, and -1 is used because no index is ever negative.
⚡ How many steps: O(n)
Guess first: how many checks does it take to look for 6 in [4, 2, 7, 1, 9, 3, 8, 5]?
8 checks. 6 is not in that array, so every item gets checked before the answer is -1.
Meaning: The best case (the value is at index 0) takes one check. In the worst case (the value is at the end or not there), every item is checked. So linear search is O(n), where n is the amount of data: double the data, and the time roughly doubles.
⚡ When to use linear search
Meaning: Linear search fits data that isn't sorted and only needs searching once, small data, or a condition that isn't "exactly equal" (for example, the first price under $50). Binary search is much faster, but it needs sorted data, and sorting the data first takes more steps than one linear search.