80 using bits_t = std::make_unsigned_t<
81 std::remove_cvref_t<std::invoke_result_t<P, std::iter_value_t<R>>>>;
82 constexpr bits_t _BITS = BITS;
85 using T = std::iter_value_t<R>;
88 using I = std::remove_cvref_t<std::invoke_result_t<P, T>>;
89 using uI = std::make_unsigned_t<I>;
91 if constexpr (!std::is_same_v<uI, I>)
98 if (range.size() <= 1)
102 constexpr uI bucket_size = 1 << _BITS;
103 uI mask = (uI(1) << _BITS) - 1;
104 constexpr uI top_bit = uI(1) << (
sizeof(uI) * 8 - 1);
111 std::array<I, bucket_size> counter{};
112 std::array<I, bucket_size> offset;
119 bool all_first_bit =
true;
120 for (
const auto& e : range)
123 max_value = std::max(max_value, v);
124 all_first_bit = all_first_bit && (v & top_bit);
129 max_value = max_value & ~top_bit;
141 std::vector<T> buffer(range.size());
142 std::span<T> current_perm = range;
143 std::span<T> next_perm = buffer;
144 for (I i = 0; i < its; i++)
149 std::ranges::fill(counter, 0);
152 for (
auto c : current_perm)
153 counter[(proj(c) & mask) >> mask_offset]++;
158 std::exclusive_scan(counter.begin(), counter.end(), offset.begin(), I(0));
159 for (
auto c : current_perm)
161 uI bucket = (proj(c) & mask) >> mask_offset;
162 next_perm[offset[bucket]++] = c;
165 mask = mask << _BITS;
166 mask_offset += _BITS;
168 std::swap(current_perm, next_perm);
173 std::ranges::copy(buffer, range.begin());
187std::vector<std::int32_t>
sort_by_perm(std::span<const T> x, std::size_t shape1)
189 static_assert(std::is_integral_v<T>,
"Integral required.");
192 return std::vector<std::int32_t>{};
195 assert(x.size() % shape1 == 0);
196 const std::size_t shape0 = x.size() / shape1;
197 std::vector<std::int32_t> perm(shape0);
198 std::iota(perm.begin(), perm.end(), 0);
202 std::vector<T> column(shape0);
203 for (std::size_t i = 0; i < shape1; ++i)
205 std::size_t col = shape1 - 1 - i;
206 for (std::size_t j = 0; j < shape0; ++j)
207 column[j] = x[j * shape1 + col];
209 {
return column.get()[index]; });
constexpr void radix_sort(R &&range, P proj={})
Sort a range with radix sorting algorithm. The bucket size is determined by the number of bits to sor...
Definition sort.h:78
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:187