Linear search
Easy TimeO(n) SpaceO(1)
Given an array arr, in no particular order, and a target, return the index of the first element equal to it, or -1 when it never appears. Comparison is by value.
Examples
Example 1
- Input
- arr = [4, 2, 7, 1, 9]target = 7
- Output
- 7 sits at index 2, after the 4 and the 2.
2
Example 2
- Input
- arr = [2, 7, 2]target = 2
- Output
- 2 is at index 0 and again at index 2, and the first one is wanted.
0
The Code
function linearSearch(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) return i;
}
return -1;
}
linearSearch([4, 2, 7, 1, 9], 7);Done
More like this
All searching examples (8) →- Binary search Halve the search range each step with lo / mid / hi.
- Rotated search Binary search where one half is always sorted — use it.
- Find peak Climb toward the higher neighbour — a peak must lie that way.
- Binary search (recursive) The same halving, written as a call tree instead of a loop.
- Insert position Binary search that returns where a value *would* go.
- Search on the answer Binary search the answer space, not the array.