cocktail.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_COKTAIL_HXX
21 #define MODULE_SORT_COKTAIL_HXX
22 
23 // STD includes
24 #include <iterator>
25 
26 namespace huc
27 {
28  namespace sort
29  {
40  template <typename IT, typename Compare = std::less<typename std::iterator_traits<IT>::value_type>>
41  void Cocktail(const IT& begin, const IT& end)
42  {
43  const auto distance = static_cast<const int>(std::distance(begin, end));
44  if (distance < 2)
45  return;
46 
47  int beginIdx = 0;
48  int endIdx = distance - 1;
49  bool hasSwapped = true;
50  while (hasSwapped && beginIdx < distance - 1)
51  {
52  hasSwapped = false;
53  // for each element from beginning - bubble it up until the end.
54  for (auto it = begin + beginIdx; it < begin + endIdx; ++it)
55  if (Compare()(*(it + 1), *it))
56  {
57  std::swap(*it, *(it + 1));
58  hasSwapped = true;
59  }
60  --endIdx;
61 
62  if (!hasSwapped)
63  break;
64 
65  // for each element from the end- bubble it down until the beginning.
66  for (auto it = begin + endIdx - 1; it >= begin + beginIdx; --it)
67  if (Compare()(*(it + 1), *it))
68  {
69  std::swap(*it, *(it + 1));
70  hasSwapped = true;
71  }
72 
73  ++beginIdx;
74  }
75  }
76  }
77 }
78 
79 #endif // MODULE_SORT_COKTAIL_HXX
void Cocktail(const IT &begin, const IT &end)
Definition: cocktail.hxx:41