LINEAR SEARCH ALGORITHM STEP BY STEP
🎯 What is Linear Search?
Linear Search is a simple searching technique used to find an element in a list or array by checking each element one by one from the beginning to the end.
📌 Definition
Linear Search is a sequential searching algorithm where each element is compared with the target value until a match is found or the list ends.
🧠 How Linear Search Works
- Start from the first element
- Compare each element with the target value
- If match found → Stop
- If not found → Move to next element
- Continue until end of list
📊 Example
Array:
A = [10, 25, 30, 45, 60]
Target:
Find 30
Step-by-step Process:
| Step | Element Checked | Result |
|---|---|---|
| 1 | 10 | Not match |
| 2 | 25 | Not match |
| 3 | 30 | ✅ Match found |
💻 Algorithm (Pseudocode)
LinearSearch(A, n, key)
1. for i = 0 to n-1
2. if A[i] == key
3. return i
4. return -1
🐍 Linear Search Program (Python)
def linear_search(arr, key):
for i in range(len(arr)):
if arr[i] == key:
return i
return -1
# Example
arr = [10, 25, 30, 45, 60]
key = 30
result = linear_search(arr, key)
if result != -1:
print("Element found at index:", result)
else:
print("Element not found")
Output:
Element found at index: 2
⚡ Best Case, Worst Case
| Case | Condition | Complexity |
|---|---|---|
| Best Case | Element at first position | O(1) |
| Worst Case | Element at last or not present | O(n) |
| Average Case | Random position | O(n) |
📌 Advantages of Linear Search
- Very simple to understand
- Works on unsorted data
- No extra memory required
❌ Disadvantages
- Slow for large data sets
- Not efficient compared to binary search
🆚 Linear Search vs Binary Search
| Feature | Linear Search | Binary Search |
|---|---|---|
| Data Requirement | Unsorted | Sorted |
| Speed | Slow | Fast |
| Method | Sequential | Divide & Conquer |
🧠 Real Life Example
- Searching a name in attendance register
- Finding a contact in phone list (unsorted)
📌 Summary
- Linear search checks elements one by one.
- It is simple but inefficient for large data.
- Best used for small or unsorted datasets.
❓ Important Questions
Short Questions
- What is linear search?
- What is time complexity of linear search?
- Give one advantage of linear search.
- Is sorting required in linear search?
- Write one real-life example.
Long Questions
- Explain linear search with example.
- Write algorithm of linear search.
- Write a program for linear search.
- Compare linear and binary search.
- Explain best and worst case of linear search.
No comments:
Post a Comment