AceCommon
1.4.5
Arduino library for low-level common functions and features with no external dependencies
src
algorithms
isSorted.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
32
#ifndef ACE_COMMON_IS_SORTED_H
33
#define ACE_COMMON_IS_SORTED_H
34
35
namespace
ace_common {
36
58
template
<
typename
K>
59
bool
isSortedByKey
(
size_t
size, K&& key) {
60
if
(size == 0)
return
false
;
61
62
auto
prev = key(0);
63
for
(
size_t
i = 1; i < size; ++i) {
64
auto
current = key(i);
65
if
(current < prev)
return
false
;
66
prev = current;
67
}
68
return
true
;
69
}
70
83
template
<
typename
X>
84
bool
isSorted
(
const
X list[],
size_t
size) {
85
if
(size == 0)
return
false
;
86
87
auto
prev = list[0];
88
for
(
size_t
i = 1; i < size; ++i) {
89
auto
current = list[i];
90
if
(current < prev)
return
false
;
91
prev = current;
92
}
93
return
true
;
94
95
#if 0
96
// This shorter alternative runs a lot slower on many platforms because the
97
// compiler is not able to optimize away the lambda expression and so the
98
// isSortedByKey() makes a function call on each iteration.
99
return
isSortedByKey
(size,
100
[&list](
size_t
i) {
return
list[i]; }
/*key*/
);
101
#endif
102
}
103
104
}
// ace_common
105
106
#endif
ace_common::isSorted
bool isSorted(const X list[], size_t size)
Simplified version of isSortedByKey() where the elements of the array and the type returned by the ke...
Definition:
isSorted.h:84
ace_common::isSortedByKey
bool isSortedByKey(size_t size, K &&key)
Determine if the abstract array is sorted according to its 'key'.
Definition:
isSorted.h:59
Generated by
1.8.17