Overview & Concept
Linear Search (Sequential Search) is the simplest search algorithm. It inspects every element in a collection one by one from beginning to end until a match is found or the collection is exhausted. It requires zero pre-conditions and operates on both unsorted and sorted data structures.
How It Works
Sequential Scanning: Begins at index 0 and advances incrementally to index n - 1.
Element Comparison: Evaluates current element A[i] against target value.
Immediate Termination: Returns index i immediately upon match detection.
Exhaustion Check: If loop reaches end of array without matching, returns -1 (not found).
Step-by-Step Execution
Asymptotic Complexity Analysis
| Metric | Best Case | Average Case | Worst Case | Space Complexity |
|---|---|---|---|---|
| Complexity Bound | O(1) | O(n) | O(n) | O(1) |
| Explanation | Optimal input arrangement minimizing operations. | Expected time for uniformly distributed randomized inputs. | Adversarial degenerate conditions requiring full traversal. | Auxiliary memory allocated beyond original input size. |
Pseudocode & Invariants
procedure linearSearch(A, target):
for i = 0 to length(A) - 1:
if A[i] == target:
return i // target found
end for
return -1 // target not found- Absence Invariant: For all k < i, A[k] != target.
Advantages & Disadvantages
Key Advantages
- •Works on unsorted arrays and linked lists without prior preparation.
- •O(1) auxiliary space.
- •O(1) best case if target is at index 0.
Trade-offs & Limitations
- •O(n) linear search time: slow for large datasets.
Real-World Applications
Searching Unsorted Small Lists
Looking up items in small configs or user inputs.
Single-Pass Streaming Filters
Searching logs or streaming network packets.
Decision Guide: When to Use
Ideal Scenarios
- ✓When the collection is unsorted and will only be searched once or twice.
- ✓When collection size is very small (n < 20).
Consider Alternatives When
- ✕When performing repeated searches on large datasets (sort once and use Binary Search or Hash Table).
Explore Related Algorithms
Compare trade-offs and complexity across complementary tools in AlgoViz.