partition.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_SORT_PARTITION_HXX
21 #define MODULE_SORT_PARTITION_HXX
22 
23 // STD includes
24 #include <iterator>
25 
26 namespace huc
27 {
28  namespace sort
29  {
42  template <typename IT, typename Compare = std::less_equal<typename std::iterator_traits<IT>::value_type>>
43  IT Partition(const IT& begin, const IT& pivot, const IT& end)
44  {
45  if (std::distance(begin, end) < 2 || pivot == end)
46  return pivot;
47 
48  auto pivotValue = *pivot; // Keep the pivot value;
49  std::swap(*pivot, *(end - 1)); // Put the pivot at the end for convenience
50  auto store = begin; // Put the store pointer at the beginning
51 
52  // Swap each smaller before the pivot item
53  for (auto it = begin; it != end - 1; ++it)
54  {
55  if (Compare()(*it, pivotValue))
56  {
57  std::swap(*store, *it);
58  ++store;
59  }
60  }
61 
62  // Replace the pivot at its good position
63  std::swap(*(end - 1), *store);
64 
65  return store;
66  }
67  }
68 }
69 
70 #endif // MODULE_SORT_PARTITION_HXX
IT Partition(const IT &begin, const IT &pivot, const IT &end)
Definition: partition.hxx:43