A Simple Explanation of Linear Searching in Data Structures

Imagine you're looking for a specific book on a shelf. The books are not organized in any particular order—they are just randomly placed on the shelf.

  1. Start at the first book on the shelf.

  2. If it’s the book you're looking for, you're done.

  3. If it’s not the right book, move to the next book on the shelf and check again.

  4. Repeat until you either find the book or reach the end of the shelf.

In programming terms, you are checking each item in the list one by one until you find the target or exhaust all the items.

Time Complexity of Linear Search

Best Case Scenario:

You are looking for a book, and it's the first book on the shelf. You check the first book and find it instantly.

In Code Terms:

  • In the first comparison, the algorithm finds the target. So, it exits right away.

Time Complexity:

  • The best case occurs when the target element is at the very first position in the array (or list). In this case, the Linear Search takes only one comparison.

  • Best Case Time Complexity: O(1) (constant time) because the search terminates after a single check.

Worst Case Scenario:

You are looking for a book, and it’s the last book on the shelf. You check the first book, then the second, then the third, and so on, until you reach the last book.

In Code Terms:

  • The algorithm needs to compare every element in the array until it either finds the target or checks every element.

  • Worst case occurs when the target element is the last one in the list or not in the list at all.

Time Complexity:

  • The worst case happens when the target is at the very last position or not in the list at all. In this case, the algorithm has to check every element.

  • Worst Case Time Complexity: O(n), where n is the number of elements in the array. This means the time taken increases linearly with the size of the list.

Average Case:

Let’s say the book you’re looking for is somewhere in the middle of the shelf. You might check a few books before you find it.

In Code Terms:

  • On average, Linear Search checks about half of the elements in the list before finding the target.

Time Complexity:

  • The average case time complexity is also O(n), but since it’s usually somewhere in the middle, the average number of comparisons is about n/2.

  • Average Case Time Complexity: O(n). Even though it’s a bit more efficient than the worst case, we still say it’s O(n) because we ignore constant factors.

Summary of Time Complexity:

ScenarioExplanationTime Complexity
Best CaseTarget is at the first position.O(1)
Worst CaseTarget is at the last position or not in the list.O(n)
Average CaseTarget is somewhere in the middle.O(n)
0
Subscribe to my newsletter

Read articles from Sumaiya Akter Ria directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sumaiya Akter Ria
Sumaiya Akter Ria