Skip to content

Linear Search


Task: Find 23 in this unsorted array

01234567314681756114223RESULT7index8 comparisons - every value in the arrayi

Analogy

  • Imagine you're looking for a specific book on a messy shelf.
  • You check each book one by one until you find the right one.
  • That's exactly how Linear Search works.

Definition

  • Linear Search is a method to find an element in a list/array.
  • It checks each element sequentially until the target is found or the list ends.
  • Example: Searching for 25 in [10, 20, 25, 30].

Step-by-step process

  1. Start at the first element

  2. Compare it with the target value

  3. If it matches → return index

  4. If not → move to the next element

  5. Continue until found or list ends


Example in code

C++
int linearSearch(int arr[], int n, int key) { for(int i = 0; i < n; i++) {    if(arr[i] == key) return i; // found } return -1; // not found}

Complexity

CaseTimeWhy
Best caseO(1)Target is the first element.
Worst caseO(n)Target is last or not present.
Average caseO(n)Roughly half the list checked.

Advantages

  • Simple to understand and implement.
  • Works on unsorted lists.
  • No extra memory required.

Limitations

  • Slow for large datasets.
  • Inefficient compared to algorithms like Binary Search.

🎯 Quick recap

Key takeaway

  • Linear Search = check items one by one.
  • Easy but inefficient for big lists.
  • Complexity: O(n) in worst case.