Skip to content

Commit dc7b822

Browse files
committed
Use with_bit_floor in radix sort
1 parent 52d8541 commit dc7b822

File tree

2 files changed

+22
-8
lines changed

2 files changed

+22
-8
lines changed

Diff for: cp-algo/util/bit.hpp

+10
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,15 @@ namespace cp_algo {
1515
size_t kth_set_bit(uint64_t x, size_t k) {
1616
return std::countr_zero(_pdep_u64(1ULL << k, x));
1717
}
18+
template<int fl = 0>
19+
void with_bit_floor(size_t n, auto &&callback) {
20+
if constexpr (fl >= 63) {
21+
return;
22+
} else if (n >> (fl + 1)) {
23+
with_bit_floor<fl + 1>(n, callback);
24+
} else {
25+
callback.template operator()<1ULL << fl>();
26+
}
27+
}
1828
}
1929
#endif // CP_ALGO_UTIL_BIT_HPP

Diff for: cp-algo/util/sort.hpp

+12-8
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
#ifndef CP_ALGO_UTIL_SORT_HPP
22
#define CP_ALGO_UTIL_SORT_HPP
3+
#include "bit.hpp"
34
#include <algorithm>
45
#include <numeric>
56
#include <ranges>
67
#include <vector>
78
namespace cp_algo {
8-
void count_sort(auto &a, size_t maxc, auto &&proj = std::identity{}) {
9-
std::vector<int> cnt(maxc);
9+
template<size_t maxc>
10+
void count_sort(auto &a, auto &&proj = std::identity{}) {
11+
std::array<int, maxc> cnt = {};
1012
for(auto &x: a) {
1113
cnt[proj(x)]++;
1214
}
@@ -22,13 +24,15 @@ namespace cp_algo {
2224
if(empty(a)) {
2325
return;
2426
}
25-
int base = std::bit_floor(size(a));
2627
auto mx = std::ranges::max(a);
27-
for(int64_t i = 1; i <= mx; i *= base) {
28-
count_sort(a, base, [&](auto x) {
29-
return x / i % base;
30-
});
31-
}
28+
with_bit_floor(size(a), [&]<size_t floor>() {
29+
constexpr int base = std::min<size_t>(floor, 1 << 16);
30+
for(int64_t i = 1; i <= mx; i *= base) {
31+
count_sort<base>(a, [&](auto x) {
32+
return x / i % base;
33+
});
34+
}
35+
});
3236
}
3337
}
3438
#endif // CP_ALGO_UTIL_SORT_HPP

0 commit comments

Comments
 (0)