LINEAR SEARCH

Introduction

Linear or Sequential Search Algorithm is a method for finding an element within a given data structure. It sequentially checks each element until the match is found or whole list has been scanned.

Let's look at the working of this algorithm.

Working Procedure

Do refer the code available the end of this section to understand the following theory.

  1. Consider an array of n elements.
  2. Create a temporary variable called pos to store the index of the searching element(if found) and initially assign it to -1.
  3. Loop through the array from 0 to n-1.
  4. Check if array element is equal to the element to be searched.
  5. If it matches then assign this index+1 to pos variable and break the loop.
  6. After looping, if pos value is still -1 then it means that the element is not found in the given array.
  7. If it's not -1 then element is found the position whose value is pos.

Time Complexity

PS: We give random inputs because the no. of input will generally be 100 or 1000 to find the time complexity and manually giving so many inputs is cumbersome work.

The basic operation in this algorithm is the comparision between each array element and the element to be searched(step 3 in the above working procedure). So increment the count variable above this if condition to get the count of no. of times the basic operation has been performed.

Linear Search

Time Complexity: O(n)

Similar posts: Binary Search

Code file

Please open this in your pc or with a compatible app in your mobile.

C++ Implementation for LINEAR SEARCH

That's it from this blog post. If you liked it then do share this blog with your friends or people who wanna get into programming world. Thank You!

Copyright © NStF Blogs 2021