Linear Search
What is Searching?
Searching is the process of finding a particular item (called key) from a collection of items (like an array, list, or database).
-
If the item is found, we usually return its position (index).
-
If the item is not found, we indicate that the search was unsuccessful.
Searching is very important in real-world applications like:
-
Finding a name in a contact list 📞
-
Searching a product on an online store 🛒
-
Looking up a word in a dictionary 📖
🌟 What are Search Algorithms?
Search Algorithms are special methods or procedures to locate the target value within a dataset.
Common search algorithms include:
-
Linear Search
-
Binary Search
-
Hashing-based Search
-
Search Trees (like Binary Search Trees)
🌟 Linear Search (Detailed Explanation)
-
It finds the target (success) ✅
-
Or reaches the end without finding it (failure) ❌
📋 Linear Search Algorithm
-
Start from the first element of the array.
-
Compare the target value with the current element.
-
If they are equal, return the index (element found).
-
If not, move to the next element.
-
Repeat steps 2–4 until:
-
The element is found, or
-
The entire array is traversed.
-
-
If not found after the whole array, report that the element does not exist.
📈 Time Complexity
Case | Complexity |
---|---|
Best Case (first element) | O(1) |
Worst Case (last element or not present) | O(n) |
Average Case | O(n) |
✏️ Simple Example
Suppose we have the array:
and we want to find 30
.
-
Compare 10 → no
-
Compare 25 → no
-
Compare 30 → yes! (found at index 2)
Comments
Post a Comment