codex
Loading...
Searching...
No Matches
selection.hpp
Go to the documentation of this file.
1#ifndef CODEX_SORT_SELECTION_H
2#define CODEX_SORT_SELECTION_H
3
4#include <algorithm>
5#include <cassert>
6
7namespace codex {
8
9template<std::input_iterator I, std::sentinel_for<I> S>
10constexpr bool is_range(I b, S e) {
11 if constexpr(!std::random_access_iterator<I>)
12 return true;
13 else if constexpr(!std::random_access_iterator<S>)
14 return true;
15 else
16 return b <= e;
17}
18
19template<std::input_iterator I, std::sentinel_for<I> S>
20constexpr I min_element(I b, S e) {
21 constexpr bool fwd = std::forward_iterator<I>;
22 assert(is_range(b, e));
23 if(b == e)
24 return e;
25 auto ret = b;
26 for(auto i = std::next(ret); i != e; ++i) {
27 if constexpr(fwd)
28 assert(std::min_element(b, i) == ret);
29 if(*i < *ret)
30 ret = i;
31 }
32 assert(b <= ret && ret < e);
33 if constexpr(fwd)
34 assert(is_min_element(b, e, *ret));
35 return ret;
36}
37
38template<std::permutable I, std::sentinel_for<I> S>
39constexpr void selection_sort(I b, S e) {
40 assert(is_range(b, e));
41 for(auto i = b; i != e; ++i) {
42 assert(std::is_sorted(b, i));
43 if(auto m = min_element(i, e); m != i)
44 std::iter_swap(i, m);
45 assert(std::is_partitioned(
46 b, e, [i](const auto &x) { return x < *i; }));
47 }
48 assert(std::is_sorted(b, e));
49}
50
51}
52
53#endif
static const struct board b
Definition chess0.c:57
#define x
Definition gcc14.c:1
Definition rotate.hpp:6
constexpr I min_element(I b, S e)
Definition selection.hpp:20
constexpr void selection_sort(I b, S e)
Definition selection.hpp:39
constexpr bool is_range(I b, S e)
Definition selection.hpp:10
#define m(a)
Definition std2.c:8
Definition reflexpr.cpp:168
Definition mult_inh.c:26
constexpr bool is_min_element(I b, S e, const auto &x)
Definition utils.hpp:35