VOOZH about

URL: https://www.geeksforgeeks.org/cpp/cpp-program-for-linear-search/

⇱ C++ Program For Linear Search - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C++ Program For Linear Search

Last Updated : 23 Jul, 2025

Linear search algorithm is the simplest searching algorithm that is used to find an element in the given collection. It simply compares the element to find with each element in the collection one by one till the matching element is found or there are no elements left to compare.

In this article, we will learn about linear search algorithm and how to implement it in C++.

Linear Search Using Library Function

C++ STL provides the std::find() function that implements the linear search algorithm to find an element in some container or array. This function returns the pointer/iterator to the element if found, otherwise, it returns the pointer/iterator to the end.

Note: std::find() function performs linear search with arrays, vectors and lists. For ordered and unordered data containers such as map, unordered_map, etc. it searches for the given element according to the search performance of the container.


Output
30 Found at Position: 3

Time Complexity: O(n), where n is the number of elements
Auxiliary Space: Implementation defined, discussed below

Manually Implement Linear Search in C++

We can also manually implement the linear search in C++ by using both iteration and recursion. But first, we need to understand the working of linear search:

Working of Linear Search

The working of linear search is simple. We compare the element to find with each element in the given collection one by one starting from the first element. If the element is found, we return its index and stop the search. Otherwise, if we reach the end of the collection without finding the element, we return some other value denoting that the element is not found in the given collection.

Iterative Implementation


Output
6

Time Complexity: O(n), where n is the number of elements
Auxiliary Space: O(1)

Recursive Implementation


Output
8 Found at Position: 6

Time Complexity: O(n), where n is the number of elements
Auxiliary Space: O(n), for recursion stack.

Comment