Task 3 of 6
One bit per pass means 32 passes for a 32-bit key. Four bits per pass means 16 buckets and eight passes — the same total work rearranged, with far fewer round trips. That is the real engineering trade in radix sorting, and every library picks a number here (4 and 8 bits are the usual answers).
The price is that the bucket table stops being a single number. You need a
histogram — how many keys carry each of the 16 digits — and then a
running total across the buckets to turn those counts into starting offsets:
bucket b begins after every key whose digit is smaller than b.
Both of those are primitives in their own right (and each has a module of its own); at 16
buckets they are small enough to write out in a loop.
Note the word smaller. The scan is exclusive: bucket 0 starts
at slot 0, and bucket b's offset stops at b − 1. Include your own
count and every bucket starts one whole bucket too far along.
histogram counts the keys in
each of the 16 digit buckets at a given place, and offsets turns
those counts into starting slots with an exclusive scan.place is Math.floor(key / place) % this.constants.radixhistogram: 16 threads, thread b counts the keys whose digit is boffsets: thread b totals counts[0 … b−1] — exclusive, so offsets[0] is 0place selects which digit you want: 1 for the ones
digit, 16 for the sixteens, 256 for the next. Divide it away,
then take what is left modulo the radix:
const d = Math.floor(keys[i] / place) % this.constants.radix;
Skip the % 16 and d is the whole quotient, not a digit.
You cannot walk the keys and bump a counter — that is 64 threads fighting over
16 cells. Invert it: each of the 16 threads owns one bucket and walks the whole key
array counting its own digit. if (d === this.thread.x) count++;
for (let b = 0; b < this.constants.radix; b++) {
if (b < this.thread.x) start += counts[b];
}
Sixteen values is far too few to be worth a clever scan; the point is the
b < this.thread.x.
This page is an interactive exercise — the editor, the GPU runner and your saved progress need JavaScript. The text above is the full brief.