binary.hxx
Go to the documentation of this file.
1 /*===========================================================================================================
2  *
3  * SHA - Simple Hybesis Algorithms
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/michael-jeulinl/Simple-Hybesis-Algorithms/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 SHA_Search
27 {
35 
42  template <typename IT, typename IsEqual>
43  int BinarySearch(const IT& begin, const IT& end, const typename std::iterator_traits<IT>::value_type& key)
44  {
45  int index = -1;
46  auto lowIt = begin;
47  auto highIt = end;
48  auto middleIt = lowIt + std::distance(lowIt, highIt) / 2;
49 
50  // While there is still objects between the two ITs and no object has been foud yet
51  while(lowIt < highIt && index < 0)
52  {
53  // Found object - Set index computed from initial begin IT
54  if (IsEqual()(key, *middleIt))
55  {
56  index = static_cast<int>(std::distance(begin, middleIt));
57  break;
58  }
59  // Search key within upper collection
60  else if (key > *middleIt)
61  lowIt = middleIt + 1;
62  // Search key within lower collection
63  else
64  highIt = middleIt;
65 
66  middleIt = lowIt + std::distance(lowIt, highIt) / 2;
67  }
68 
69  return index;
70  }
71 }
72 
73 #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:43