Linear search is the simplest search algorithm that checks each element in a list sequentially until the target value is found or the end of the list is reached.Documentation Index
Fetch the complete documentation index at: https://mintlify.com/dfernandeza/data-structures-and-algorithms/llms.txt
Use this file to discover all available pages before exploring further.
Algorithm overview
Linear search works by iterating through each element in the list from start to end, comparing each element with the target value. When a match is found, the index is returned. If no match is found after checking all elements, the algorithm returns -1.Key characteristics
- Works on both sorted and unsorted arrays
- Simple to implement and understand
- No preprocessing required
- Best for small datasets or unsorted data
Implementation
The linear search implementation uses a simple loop to check each element:linear-search.ts
Function signature
Complexity analysis
Time complexity
Time complexity
- Best case: O(1) - Element is at the first position
- Average case: O(n) - Element is somewhere in the middle
- Worst case: O(n) - Element is at the end or not present
Space complexity
Space complexity
O(1) - Constant spaceThe algorithm only uses a single loop variable regardless of input size.
Usage examples
Basic usage
Searching strings
Searching objects
Linear search uses strict equality (
===) for comparison. For custom comparison logic or searching objects by properties, you’ll need to implement a custom search function.When to use linear search
Good for
- Small datasets (< 100 elements)
- Unsorted arrays
- Single searches
- When simplicity matters
Avoid when
- Large sorted datasets
- Multiple searches on same data
- Performance is critical
- Data can be preprocessed
Advantages and disadvantages
Advantages
- Simple to implement and understand
- Works on unsorted data
- No preprocessing or additional memory required
- Works with any data type that supports equality comparison
Disadvantages
- Inefficient for large datasets
- Slower than other algorithms for sorted data
- No way to optimize for repeated searches
Related algorithms
Binary search
Much faster O(log n) search for sorted arrays
Depth-first search
Graph and tree traversal algorithm