TRIQS/itertools 1.3.0
C++ range library
Loading...
Searching...
No Matches
sort.hpp
Go to the documentation of this file.
1// Copyright (c) 2024 Simons Foundation
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0.txt
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//
15// Authors: Thomas Hahn, Olivier Parcollet, Nils Wentzell, chuffa
16
21
22#ifndef _ITERTOOLS_SORT_HPP
23#define _ITERTOOLS_SORT_HPP
24
25#include <algorithm>
26#include <cstddef>
27#include <functional>
28#include <iterator>
29#include <ranges>
30
31namespace itertools {
32
37
56 template <std::forward_iterator ForwardIt, class Compare = std::less<>>
57 std::size_t bubble_sort(ForwardIt first, ForwardIt last, Compare comp = {}) {
58 if (first == last) { return 0; }
59 std::size_t n_swaps = 0;
60 for (ForwardIt sorted = first; first != last; last = sorted) {
61 sorted = first;
62 for (ForwardIt curr = first, prev = first; ++curr != last; ++prev) {
63 if (comp(*curr, *prev)) {
64 std::iter_swap(curr, prev);
65 sorted = curr;
66 ++n_swaps;
67 }
68 }
69 }
70 return n_swaps;
71 }
72
91 template <std::bidirectional_iterator BidirIt, class Compare = std::less<>>
92 std::size_t insertion_sort(BidirIt first, BidirIt last, Compare comp = {}) {
93 if (first == last) { return 0; }
94 std::size_t swaps = 0;
95 for (BidirIt i = std::next(first); i != last; ++i) {
96 for (BidirIt j = i; j != first && comp(*j, *std::prev(j)); --j) {
97 std::iter_swap(std::prev(j), j);
98 ++swaps;
99 }
100 }
101 return swaps;
102 }
103
115 template <std::ranges::forward_range Range, class Compare = std::less<>>
116 std::size_t bubble_sort(Range &&rng, Compare comp = {}) { // NOLINT (ranges need not be forwarded)
117 return bubble_sort(std::ranges::begin(rng), std::ranges::end(rng), comp);
118 }
119
131 template <std::ranges::bidirectional_range Range, class Compare = std::less<>>
132 std::size_t insertion_sort(Range &&rng, Compare comp = {}) { // NOLINT (ranges need not be forwarded)
133 return insertion_sort(std::ranges::begin(rng), std::ranges::end(rng), comp);
134 }
135
137
138} // namespace itertools
139
140#endif // _ITERTOOLS_SORT_HPP
std::size_t bubble_sort(ForwardIt first, ForwardIt last, Compare comp={})
Bubble sort elements in the given range.
Definition sort.hpp:57
std::size_t insertion_sort(BidirIt first, BidirIt last, Compare comp={})
Insertion sort elements in the given range.
Definition sort.hpp:92