bubble.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_BUBBLE_HXX
21 #define MODULE_SORT_BUBBLE_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 Bubble(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 endIdx = -1;
48  bool hasSwapped;
49  // for each element - bubble it up until the end.
50  for (auto it = begin; it < end - 1; ++it, --endIdx)
51  {
52  hasSwapped = false;
53  for (auto curIt = begin; curIt < end + endIdx; ++curIt)
54  if (Compare()(*(curIt + 1), *curIt))
55  {
56  std::swap(*(curIt + 1), *curIt);
57  hasSwapped = true;
58  }
59 
60  if (!hasSwapped)
61  break;
62  }
63  }
64  }
65 }
66 
67 #endif // MODULE_SORT_BUBBLE_HXX
void Bubble(const IT &begin, const IT &end)
Definition: bubble.hxx:41