What is Linear Search?
Linear Search is a simple method to find a particular value in a list. It checks each element one by one from the start until it finds the target value. If the value is found, it returns its position; otherwise, it says the value is not present.
How Does It Work?
Imagine you have a list of numbers: [5, 3, 8, 1, 9] and you want to find the number 8.
- Start from the first number (5). Is 5 equal to 8? No.
- Move to the next number (3). Is 3 equal to 8? No.
- Move to the next number (8). Is 8 equal to 8? Yes! Stop here. The position is 2 (or 3 if counting starts from 1).
If the number is not in the list (e.g., searching for 10), the search ends without success.
Algorithm Steps
- Start from the first element.
- Compare the current element with the target value.
- If they match, return the position.
- If not, move to the next element.
- Repeat until the end of the list.
- If the element is not found, return "Not Found".
Time Complexity
- Best Case: Target is the first element → O(1)
- Worst Case: Target is last or not present → O(n) (checks all elements)
Linear Search is easy to understand but can be slow for large lists compared to faster methods like Binary Search.