forked from ProAlgos/ProAlgos-Cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
linear_search.hpp
37 lines (29 loc) · 864 Bytes
/
linear_search.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/*
Linear search
-------------
A searching algorithm that finds the position of a target value within an
array (sorted or otherwise).
Time complexity
---------------
O(N), where N is the number of elements in the array.
Space complexity
----------------
O(1).
*/
#ifndef LINEAR_SEARCH_HPP
#define LINEAR_SEARCH_HPP
#include <vector>
/*
linear_search
-------------
Returns the index where a given element is found in an array. If the
element is not found, it returns -1.
*/
template <typename T>
int linear_search(const T& element, const std::vector<T>& values) {
for (size_t i = 0; i < values.size(); i++)
if (values[i] == element) // it's a match!
return i; // return the index at which it was found
return -1; // no match is found
}
#endif // LINEAR_SEARCH_HPP