kth_max_element.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_MAX_KTH_ELEMENT_HXX
21 #define MODULE_SEARCH_MAX_KTH_ELEMENT_HXX
22 
23 #include <Sort/partition.hxx>
24 
25 // STD includes
26 #include <iterator>
27 
28 namespace SHA_Search
29 {
49  template <typename IT, typename Compare = std::less_equal<typename std::iterator_traits<IT>::value_type>>
50  IT MaxKthElement(const IT& begin, const IT& end, unsigned int k)
51  {
52  const auto kSize = static_cast<const int>(std::distance(begin, end));
53  if (k >= static_cast<unsigned int>(kSize))
54  return end;
55 
56  auto pivot = begin + (rand() % kSize); // Take random pivot
57  auto newPivot = SHA_Sort::Partition<IT, Compare>(begin, pivot, end); // Partition
58 
59  // Get the index of the pivot (i'th smallest/biggest value)
60  const auto kPivotIndex = std::distance(begin, newPivot);
61 
62  // Return if at the kth position
63  if (kPivotIndex == k)
64  return newPivot;
65 
66  // Recurse search on left part if there is more than k elements within the left sequence
67  // Recurse search on right otherwise
68  return (kPivotIndex > k) ? MaxKthElement<IT, Compare>(begin, newPivot, k)
69  : MaxKthElement<IT, Compare>(newPivot, end, k - kPivotIndex);
70 
71  }
72 }
73 
74 #endif // MODULE_SEARCH_MAX_KTH_ELEMENT_HXX
IT MaxKthElement(const IT &begin, const IT &end, unsigned int k)