Lesson 6 of 20
Linear Search
Linear Search
Linear Search is the simplest search algorithm. It scans each element of the array one by one until it finds the target or reaches the end.
How It Works
Start at index 0. Check each element:
- If
arr[i] === target, returni. - Otherwise, move to the next element.
- If the end is reached without finding the target, return
-1.
function linearSearch(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) return i;
}
return -1;
}
Complexity
| Case | Time | Space |
|---|---|---|
| Best (first element) | O(1) | O(1) |
| Average | O(n) | O(1) |
| Worst (not found) | O(n) | O(1) |
Linear search works on unsorted arrays and any collection where elements can be compared one at a time. It is the only option when the array is unsorted or when you have a linked list (no random access).
When to Use It
- The array is small (n < 100).
- The array is unsorted and not worth sorting for a single search.
- You are searching a linked list.
- The search criterion is complex and not easily expressed as a comparison.
Your Task
Implement linearSearch(arr, target) that returns the index of target in arr, or -1 if not found.
JavaScript loading...
Loading...
Click "Run" to execute your code.