Linear search, also known as sequential search, is a fundamental algorithm used to find an element in a list or array by checking each element one by one until the desired item is found or the end of the data structure is reached. It's simple yet effective for basic use cases.
How It Works
- Start at the beginning of the array
- Compare the target value with the current element
- If match, return the index
- If not, move to the next element
- Repeat until the end or a match is found
Time Complexity
- Best Case: O(1) ✅ (element found at first position)
- Average Case: O(n) ⏳ (element found halfway through)
- Worst Case: O(n) ⚠️ (element not found or at last position)
Use Cases
- Searching in unsorted data
- Small datasets where simplicity is prioritized
- Situations where additional memory is limited
Comparison with Binary Search
Feature | Linear Search | Binary Search |
---|---|---|
Time Complexity | O(n) | O(log n) |
Requires Sorting | ❌ | ✅ |
Memory Usage | Low | Low |
For deeper insights, explore our guide on binary search. 📚