DSA Linear Search

DSA Tutorial

 DSA Linear Search – Complete Beginner Guide

(Concept • Manual Run-Through • Algorithm • Code • Time Complexity)

Linear Search is the simplest searching algorithm in Data Structures & Algorithms (DSA).
It checks each element one by one until the required value is found or the list ends.


1️⃣ What is Linear Search?

Linear Search:

  • Searches an element by scanning sequentially

  • Starts from the first element

  • Compares each element with the target value

  • Stops when:

    • Element is found ✅

    • Array ends ❌

📌 Also called Sequential Search.


2️⃣ Simple Idea (One Line)

Check every element until the value is found


3️⃣ When to Use Linear Search?

✔ Small datasets
✔ Unsorted arrays
✔ Simple implementation required
❌ Large datasets (slow)


4️⃣ Linear Search – Manual Run-Through

 Given Array

[10, 23, 45, 70, 11, 15]

Target Value

15

Step-by-Step Search

StepCompared ValueMatch?
110
223
345
470
511
615✅ Found

📌 Element 15 found at index 5.


5️⃣ Linear Search Algorithm (Steps)

  1. Start

  2. Take input array and target value

  3. Compare target with each element from index 0

  4. If match found → return index

  5. If end reached → return not found

  6. Stop


6️⃣ Pseudocode

for i = 0 to n-1
if arr[i] == key
return i
return -1

7️⃣ Linear Search Implementation (C++)


 

Output

Element found at index 5

8️⃣ Time Complexity of Linear Search

CaseConditionTime Complexity
Best CaseElement at first indexO(1)
Average CaseElement in middleO(n)
Worst CaseLast index or not presentO(n)

📌 Must check all elements in worst case.


9️⃣ Space Complexity

MetricValue
Extra SpaceO(1)
TypeIn-place

🔟 Advantages of Linear Search

✔ Very easy to understand
✔ Works on unsorted arrays
✔ No extra memory needed
✔ Useful for small lists


1️⃣1️⃣ Disadvantages of Linear Search

❌ Slow for large datasets
❌ Inefficient compared to Binary Search
❌ Repeated comparisons


1️⃣2️⃣ Linear Search vs Binary Search

FeatureLinear SearchBinary Search
Data OrderAnyMust be sorted
SpeedSlowFast
Time ComplexityO(n)O(log n)
ImplementationEasyModerate

 Exam / Interview Questions (Linear Search)

Q1. Is Linear Search used on sorted arrays?
👉 Yes, but not efficient

Q2. Worst-case time complexity?
👉 O(n)

Q3. When should Linear Search be used?
👉 Small or unsorted datasets


 Final Summary

✔ Linear Search checks elements one by one
✔ Simple and intuitive
✔ Works on any array
✔ Time Complexity: O(n)
✔ Space Complexity: O(1)
✔ Best for beginners and small datasets

You may also like...