![]() |
VOOZH | about |
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++.
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.
30 Found at Position: 3
Time Complexity: O(n), where n is the number of elements
Auxiliary Space: Implementation defined, discussed below
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:
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.
6
Time Complexity: O(n), where n is the number of elements
Auxiliary Space: O(1)
8 Found at Position: 6
Time Complexity: O(n), where n is the number of elements
Auxiliary Space: O(n), for recursion stack.