50 std::ranges::random_access_range R,
typename P = std::identity,
51 std::remove_cvref_t<std::invoke_result_t<P, std::iter_value_t<R>>> BITS
53 requires std::integral<
decltype(BITS)>
54 constexpr void operator()(R&& range, P proj = {})
const
57 using T = std::iter_value_t<R>;
60 using I = std::remove_cvref_t<std::invoke_result_t<P, T>>;
62 if (range.size() <= 1)
65 T max_value = proj(*std::ranges::max_element(range, std::less{}, proj));
68 constexpr I bucket_size = 1 << BITS;
69 T mask = (T(1) << BITS) - 1;
81 std::array<I, bucket_size> counter;
82 std::array<I, bucket_size + 1> offset;
85 std::vector<T> buffer(range.size());
86 std::span<T> current_perm = range;
87 std::span<T> next_perm = buffer;
88 for (I i = 0; i < its; i++)
91 std::ranges::fill(counter, 0);
94 for (
const auto& c : current_perm)
95 counter[(proj(c) & mask) >> mask_offset]++;
99 std::partial_sum(counter.begin(), counter.end(),
100 std::next(offset.begin()));
101 for (
const auto& c : current_perm)
103 I bucket = (proj(c) & mask) >> mask_offset;
104 I new_pos = offset[bucket + 1] - counter[bucket];
105 next_perm[new_pos] = c;
112 std::swap(current_perm, next_perm);
117 std::ranges::copy(buffer, range.begin());
134template <
typename T,
int BITS = 16>
135std::vector<std::int32_t>
sort_by_perm(std::span<const T> x, std::size_t shape1)
137 static_assert(std::is_integral_v<T>,
"Integral required.");
140 return std::vector<std::int32_t>{};
143 assert(x.size() % shape1 == 0);
144 const std::size_t shape0 = x.size() / shape1;
145 std::vector<std::int32_t> perm(shape0);
146 std::iota(perm.begin(), perm.end(), 0);
150 std::vector<T> column(shape0);
151 for (std::size_t i = 0; i < shape1; ++i)
153 std::size_t col = shape1 - 1 - i;
154 for (std::size_t j = 0; j < shape0; ++j)
155 column[j] = x[j * shape1 + col];
157 radix_sort(perm, [&column](
auto index) {
return column[index]; });
Top-level namespace.
Definition defines.h:12
std::vector< std::int32_t > sort_by_perm(std::span< const T > x, std::size_t shape1)
Compute the permutation array that sorts a 2D array by row.
Definition sort.h:135
constexpr __radix_sort radix_sort
Radix sort.
Definition sort.h:122