AceCommon
1.4.6
Arduino library for low-level common functions and features with no external dependencies
src
algorithms
linearSearch.h
Go to the documentation of this file.
1
/*
2
MIT License
3
4
Copyright (c) 2021 Brian T. Park
5
6
Permission is hereby granted, free of charge, to any person obtaining a copy
7
of this software and associated documentation files (the "Software"), to deal
8
in the Software without restriction, including without limitation the rights
9
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
copies of the Software, and to permit persons to whom the Software is
11
furnished to do so, subject to the following conditions:
12
13
The above copyright notice and this permission notice shall be included in all
14
copies or substantial portions of the Software.
15
16
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
SOFTWARE.
23
*/
24
42
#ifndef ACE_COMMON_LINEAR_SEARCH_H
43
#define ACE_COMMON_LINEAR_SEARCH_H
44
45
#include <stdint.h>
// size_t, SIZE_MAX
46
47
namespace
ace_common {
48
66
template
<
typename
X,
typename
K>
67
size_t
linearSearchByKey
(
size_t
size,
const
X& x, K&& key) {
68
for
(
size_t
i = 0; i < size; ++i) {
69
if
(x == key(i)) {
70
return
i;
71
}
72
}
73
return
SIZE_MAX;
74
}
75
76
90
template
<
typename
X>
91
size_t
linearSearch
(
const
X list[],
size_t
size,
const
X& x) {
92
for
(
size_t
i = 0; i < size; ++i) {
93
if
(x == list[i]) {
94
return
i;
95
}
96
}
97
return
SIZE_MAX;
98
99
#if 0
100
// This shorter alternative runs a lot slower on many platforms because the
101
// compiler is not able to optimize away the lambda expression and so the
102
// linearSearchByKey() makes a function call on each iteration.
103
return
linearSearchByKey
(size, x,
104
[&list](
size_t
i) {
return
list[i]; }
/*key*/
);
105
#endif
106
}
107
108
}
// ace_common
109
110
#endif
ace_common::linearSearchByKey
size_t linearSearchByKey(size_t size, const X &x, K &&key)
Perform a linear search for element 'x' on an abstract list of records.
Definition:
linearSearch.h:67
ace_common::linearSearch
size_t linearSearch(const X list[], size_t size, const X &x)
Simplified version of linearSearchByKey() where the elements of the array and the searched element ar...
Definition:
linearSearch.h:91
Generated by
1.8.17