Linear Search Algorithm
Linear search is the most basic and intuitive searching algorithm. It finds a target value within a list by checking every element one by one, from the beginning to the end, until the target is found or all elements have been examined.
Interactive Visualization
Linear Search Visualization
Array Visualization
How Linear Search Works:
• Sequential Check: Examine each element one by one from left to right
• Compare: Check if current element equals the target value
• Early Exit: Stop immediately when target is found
• Complete Scan: If not found, check all elements
• Time Complexity: O(n) - may need to check all elements
• Space Complexity: O(1) - no additional memory needed
• Best Case: O(1) - target is the first element
• Worst Case: O(n) - target is last or not present
How Linear Search Works
Linear search, also known as sequential search, is the simplest searching algorithm. It works by examining each element in the list one after another until either the target element is found or the end of the list is reached.
1. Start
Begin at the first element of the array (index 0)
2. Compare
Check if the current element equals the target value
3. Continue or Stop
If found, return index; if not, move to next element
🔍 Sequential Element Checking Process
Step-by-Step Process
Example: Searching for 7 in [4, 2, 7, 1, 9]
✅ Advantages
- • Simple to understand and implement
- • Works on unsorted arrays
- • No preprocessing required
- • Uses constant extra space O(1)
- • Can find all occurrences easily
❌ Disadvantages
- • Inefficient for large datasets
- • Always O(n) time complexity
- • No early termination optimization
- • Not suitable for repeated searches
- • Slower than binary search on sorted data
Pseudocode
ALGORITHM LinearSearch(arr[], n, target)
BEGIN
// Iterate through each element in the array
FOR i = 0 TO n-1 DO
// Check if current element matches target
IF arr[i] == target THEN
RETURN i // Return index where target is found
END IF
END FOR
// Target not found in array
RETURN -1 // Return -1 to indicate not found
END Complexity Analysis
| Metric | Best Case | Average Case | Worst Case |
|---|---|---|---|
| Time Complexity | O(1) | O(n) | O(n) |
| Space Complexity | O(1) | O(1) | O(1) |
| Comparisons | 1 | n/2 | n |
Best Case O(1)
- • Scenario: Target is the first element
- • Comparisons: Only 1 comparison needed
- • Example: Searching for 4 in [4, 2, 7, 1, 9]
Average Case O(n)
- • Scenario: Target is somewhere in the middle
- • Comparisons: Approximately n/2 comparisons
- • Assumption: Target is equally likely to be anywhere
Worst Case O(n)
- • Scenario: Target is last element or not present
- • Comparisons: All n elements must be checked
- • Example: Searching for 9 in [4, 2, 7, 1, 9]
Why O(1) Space Complexity?
Linear search uses only a constant amount of extra memory regardless of input size. We only need a few variables (like the loop counter and target value) that don't scale with the array size, making it very memory-efficient.
Code Examples
Here are implementations of linear search in different programming languages. Each version demonstrates the sequential checking process with clear, readable code.
def linear_search(arr, target):
"""
Search for a target value in a list using linear search.
Args:
arr: List of elements to search through
target: The value to search for
Returns:
int: Index of target if found, -1 if not found
Time Complexity: O(n)
Space Complexity: O(1)
"""
# Check each element one by one
for i in range(len(arr)):
# If current element matches target, return its index
if arr[i] == target:
return i
# Target not found in the array
return -1
def linear_search_with_details(arr, target):
"""
Linear search with detailed step-by-step output.
"""
print(f"Searching for {target} in array: {arr}")
for i in range(len(arr)):
print(f"Step {i + 1}: Checking arr[{i}] = {arr[i]}")
if arr[i] == target:
print(f"Found {target} at index {i}!")
return i
else:
print(f"{arr[i]} != {target}, continue searching...")
print(f"{target} not found in the array.")
return -1
# Example usage
if __name__ == "__main__":
numbers = [4, 2, 7, 1, 9, 5, 3, 8, 6]
target = 5
result = linear_search(numbers, target)
if result != -1:
print(f"Element {target} found at index {result}")
else:
print(f"Element {target} not found in the array")
# Demonstrate with detailed output
print("\nDetailed search:")
linear_search_with_details(numbers, 7) When to Use Linear Search
Ideal Use Cases
- • Small Datasets: When array size is small (n < 100)
- • Unsorted Data: When data is not sorted and sorting is expensive
- • One-time Search: When you only need to search once
- • Simple Implementation: When code simplicity is more important than efficiency
- • Memory Constraints: When you need minimal memory usage
Avoid When
- • Large Datasets: When array size is very large (n > 1000)
- • Sorted Data Available: When binary search can be used instead
- • Frequent Searches: When you need to search the same data multiple times
- • Performance Critical: When search speed is the primary concern