-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinear-search.cpp
More file actions
38 lines (34 loc) · 1.24 KB
/
Copy pathlinear-search.cpp
File metadata and controls
38 lines (34 loc) · 1.24 KB
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
38
/**
* @file LinearSearch.cpp
* @brief Template implementation of the Linear Search algorithm.
*/
#include <iostream>
using namespace std;
/**
* @brief Searches for a target key within a fixed-size array.
* * This implementation uses template argument deduction to automatically determine
* the array size at compile time, eliminating the need to pass the size manually.
* * @tparam T The data type of the array elements (must support the == operator).
* @tparam n The size of the array, deduced by the compiler.
* @param data A reference to the array to be searched.
* @param key The target value to find.
* @return int The zero-based index of the key if found; otherwise -1.
*/
template <typename T, std::size_t n>
int linearSearch(T (&data)[n], T key)
{
// Iterate through the array to find the first occurrence of the key
for (int i = 0; i < n; i++)
{
if (data[i] == key)
{
return i; // Key found at index i
}
}
return -1; // Key not found in the array
}
/* * Technical Note:
* Using 'T (&data)[n]' passes the array by reference. This prevents the creation
* of a local copy, saving memory and ensuring that the compiler can deduce
* the size 'n' directly from the array declaration.
*/