Theory
Linear Search checks each element sequentially until the target is found or the collection ends. It works on both sorted and unsorted data. Its worst-case time complexity is O(n).
Example
const numbers = [12, 25, 7, 40, 18];
const target = 40;
let found = false;
for (const number of numbers) {
if (number === target) {
found = true;
break;
}
}
console.log(found);
Expected Output
true
Practice
Write a linear search function that returns the index of the target element.
Interview Questions
- What is linear search?
- What is its worst-case complexity?
- Can linear search work on unsorted data?
- When is linear search useful?