binary.hxx
Go to the documentation of this file.
1 /*===========================================================================================================
2  *
3  * HUC - Hurna Core
4  *
5  * Copyright (c) Michael Jeulin-Lagarrigue
6  *
7  * Licensed under the MIT License, you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * https://github.com/Hurna/Hurna-Core/blob/master/LICENSE
11  *
12  * Unless required by applicable law or agreed to in writing, software distributed under the License is
13  * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and limitations under the License.
15  *
16  * The above copyright notice and this permission notice shall be included in all copies or
17  * substantial portions of the Software.
18  *
19  *=========================================================================================================*/
20 #ifndef MODULE_SEARCH_BINARY_HXX
21 #define MODULE_SEARCH_BINARY_HXX
22 
23 // STD includes
24 #include <iterator>
25 
26 namespace huc
27 {
28  namespace search
29  {
35 
42  template <typename IT,
43  typename IsEqual = std::equal_to<typename std::iterator_traits<IT>::value_type>>
44  int BinarySearch(const IT& begin, const IT& end, const typename std::iterator_traits<IT>::value_type& key)
45  {
46  int index = -1;
47  auto lowIt = begin;
48  auto highIt = end;
49  auto middleIt = lowIt + std::distance(lowIt, highIt) / 2;
50 
51  // While there is still objects between the two ITs and no object has been foud yet
52  while(lowIt < highIt && index < 0)
53  {
54  // Found object - Set index computed from initial begin IT
55  if (IsEqual()(key, *middleIt))
56  {
57  index = static_cast<int>(std::distance(begin, middleIt));
58  break;
59  }
60  // Search key within upper collection
61  else if (key > *middleIt)
62  lowIt = middleIt + 1;
63  // Search key within lower collection
64  else
65  highIt = middleIt;
66 
67  middleIt = lowIt + std::distance(lowIt, highIt) / 2;
68  }
69 
70  return index;
71  }
72  }
73 }
74 
75 #endif // MODULE_SEARCH_BINARY_HXX
int BinarySearch(const IT &begin, const IT &end, const typename std::iterator_traits< IT >::value_type &key)
Definition: binary.hxx:44