bubble.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_SORT_BUBBLE_HXX
21 #define MODULE_SORT_BUBBLE_HXX
22 
23 // STD includes
24 #include <iterator>
25 
26 namespace SHA_Sort
27 {
46  template <typename IT, typename Compare = std::less_equal<typename std::iterator_traits<IT>::value_type>>
47  void Bubble(const IT& begin, const IT& end)
48  {
49  const auto distance = static_cast<const int>(std::distance(begin, end));
50  if (distance < 2)
51  return;
52 
53  int endIdx = -1;
54  bool hasSwapped;
55  // for each element - bubble it up until the end.
56  for (auto it = begin; it < end - 1; ++it, --endIdx)
57  {
58  hasSwapped = false;
59  for (auto curIt = begin; curIt < end + endIdx; ++curIt)
60  if (Compare()(*(curIt + 1), *curIt))
61  {
62  std::swap(*(curIt + 1), *curIt);
63  hasSwapped = true;
64  }
65 
66  if (!hasSwapped)
67  break;
68  }
69  }
70 }
71 
72 #endif // MODULE_SORT_BUBBLE_HXX
void Bubble(const IT &begin, const IT &end)
Definition: bubble.hxx:47