AceCommon  1.6.1
Arduino library for low-level common functions and features with no external dependencies
binarySearch.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 
53 #ifndef ACE_COMMON_BINARY_SEARCH_H
54 #define ACE_COMMON_BINARY_SEARCH_H
55 
56 #include <stdint.h> // size_t, SIZE_MAX
57 
58 namespace ace_common {
59 
103 template<typename X, typename K>
104 size_t binarySearchByKey(size_t size, const X& x, K&& key) {
105  size_t a = 0;
106  size_t b = size;
107  while (true) {
108  size_t diff = b - a;
109  if (diff == 0) break;
110 
111  size_t c = a + diff / 2;
112  X current = key(c);
113  if (current == x) return c;
114  if (x < current) {
115  b = c;
116  } else {
117  a = c + 1;
118  }
119  }
120  return SIZE_MAX;
121 }
122 
144 template<typename X>
145 size_t binarySearch(const X list[], size_t size, const X& x) {
146  return binarySearchByKey(size, x,
147  [&list](size_t i) { return list[i]; } /*key*/);
148 }
149 
150 } // ace_common
151 
152 #endif
size_t binarySearchByKey(size_t size, const X &x, K &&key)
Perform a binary search for element 'x' on an abstract list of records which are sorted by the 'key'.
Definition: binarySearch.h:104
size_t binarySearch(const X list[], size_t size, const X &x)
Simplified version of binarySearchByKey() where the elements of the array and the searched element ar...
Definition: binarySearch.h:145