Lesson 2 of 19
Linear search
Your ticket is in an unsorted pile. Check tickets from left to right until the number matches or the pile runs out.
A search can stop at the first match
An unsorted list gives you no clue about the next value. Each failed comparison rules out one position. If you need the first match, you can stop as soon as a comparison succeeds. To find every match, you have to keep going.
Work through an example
On the shelf [8, 4, 8, 1], how many cards do you inspect to find the first 8? What changes if you need both 8s?
Step-by-step solution
- Compare the target with index 0. It matches immediately, so a first-match search takes one comparison.
- To collect every match, continue through 4, 8 and 1. The matching indexes are 0 and 2.
- All four comparisons are necessary for the second task. An unseen card could hold another 8.
JavaScript example
function findAll(values, target) {
const matches = [];
for (let i = 0; i < values.length; i++) {
if (values[i] === target) matches.push(i);
}
return matches;
}
findAll([8, 4, 8, 1], 8); // [0, 2]DSA compiler
Try it yourself
Finish the animation to unlock this question.
Finding 2 in [9, 5, 2, 4] takes how many comparisons?
Related exercise · Largest Array Element · See this stage of the beginner path