Sane C++ Libraries
C++ Platform Abstraction Libraries
AlgorithmBubbleSort.h
1// Copyright (c) Stefano Cristiano
2// SPDX-License-Identifier: MIT
3#pragma once
4#include "../Foundation/TypeTraits.h" // RemovePointer
5
6namespace SC
7{
10
11namespace Algorithms
12{
15
17template <typename T>
19{
24 constexpr bool operator()(const T& a, const T& b) { return a < b; }
25};
26
33template <typename Iterator, typename BinaryPredicate = smallerThan<typename TypeTraits::RemovePointer<Iterator>::type>>
34constexpr void bubbleSort(Iterator first, Iterator last, BinaryPredicate predicate = BinaryPredicate())
35{
36 if (first >= last)
37 {
38 return;
39 }
40 bool doSwap = true;
41 while (doSwap)
42 {
43 doSwap = false;
44 Iterator p0 = first;
45 Iterator p1 = first + 1;
46 while (p1 != last)
47 {
48 if (predicate(*p1, *p0))
49 {
50 swap(*p1, *p0);
51 doSwap = true;
52 }
53 ++p0;
54 ++p1;
55 }
56 }
57}
59} // namespace Algorithms
60} // namespace SC
constexpr void bubbleSort(Iterator first, Iterator last, BinaryPredicate predicate=BinaryPredicate())
Sorts iterator range according to BinaryPredicate (bubble sort).
Definition: AlgorithmBubbleSort.h:34
constexpr void swap(T &t1, T &t2)
Swaps the values of two objects.
Definition: Compiler.h:282
Functor that evaluates to a < b
Definition: AlgorithmBubbleSort.h:19
constexpr bool operator()(const T &a, const T &b)
Returns true if a < b
Definition: AlgorithmBubbleSort.h:24