Linear Search
What is Linear Search?
Linear search known as sequential search. It is a simple searching algorithm that checks every element in a list or array one by one until it finds the target value or reaches the end of the list.
Best Case: O(1) - The target element is found at the first position.
Worst Case: O(n) - The target element is at the last position or not present at all.
Average Case: O(n) - On average, half of the elements need to be checked.
For space complexity, Linear Search uses O(1) space since it only requires a constant amount of additional memory for variables, regardless of the input size.
Of course, Linear Search is not the most efficient for large datasets, but it does not require the data to be sorted and is easy to implement.
- Small datasets where simplicity is preferred over efficiency
- Unsorted data
How it works?
Assuming we have an array [4, 2, 7, 1, 3] and we are searching for the target value 1:
- We start at the first element (4) and compare it to the target (1). Since they are not equal, we move to the next element.
- We compare the second element (2) to the target (1). Again, they are not equal, so we move on.
- We compare the third element (7) to the target (1). Still not equal, so we continue.
- We compare the fourth element (1) to the target (1). This time, they are equal, so we have found the target at index
3.
Implementation
def linear_search(arr: list, target: int) -> int:
for index, value in enumerate(arr):
if value == target:
return index
return -1
data = [4, 2, 7, 1, 3]
search_target = 1
result = linear_search(data, search_target)
if result != -1:
print(f"Element {search_target} found at index {result}.")
else:
print(f"Element {search_target} not found in the array.")Visualization
Linear Search
Linear Search sequentially checks each element of the array until a match is found or the entire array has been searched. It's the simplest search algorithm but not the most efficient for large datasets.
Time Complexity
- Best Case: O(1) - Element found at first position
- Average Case: O(n) - Element in middle
- Worst Case: O(n) - Element at end or not present
Space Complexity
O(1) - No extra space required
Use Cases
Best for small datasets or unsorted arrays where other search algorithms cannot be applied.