Total Pageviews

Tuesday, June 2, 2020

LINEAR SEARCH ALGORITHM STEP BY STEP

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:

StepElement CheckedResult
110Not match
225Not match
330✅ 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

CaseConditionComplexity
Best CaseElement at first positionO(1)
Worst CaseElement at last or not presentO(n)
Average CaseRandom positionO(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

FeatureLinear SearchBinary Search
Data RequirementUnsortedSorted
SpeedSlowFast
MethodSequentialDivide & 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

  1. What is linear search?
  2. What is time complexity of linear search?
  3. Give one advantage of linear search.
  4. Is sorting required in linear search?
  5. Write one real-life example.

Long Questions

  1. Explain linear search with example.
  2. Write algorithm of linear search.
  3. Write a program for linear search.
  4. Compare linear and binary search.
  5. Explain best and worst case of linear search.

No comments:

Post a Comment