Linear Search algorithm in C++ | CODELABS3277

Linear search is used on a collection of items. It relies on the technique of traversing a list from start to end by exploring properties of all the elements that are found on the way.

Implementation

  • Take a collection of elements and let k (have the value to be searched for).
  • Now traverse (go through all the elements) the collection and check whether that element is equal to k or not.
    • If equal then print "Found" and break the loop.
    • Else go till the last element and if not found then print "Not Found".
Example: Taking an array of 9 elements and searching for 4 in it.

Time Complexity
  • In this, in the worst case, we will be going to all the elements.
  • Hence the complexity is O(n) where n-number of elements in a collection.
Below is the implementation of a linear search in C++.

Comments