man bqn/sorting

How CBQN sorts: choosing an algorithm by element type

lib / BQN 12 mindraft

checked against: CBQN 2bf102f

Why does CBQN sort a million small numbers in under half a millisecond one time and take 70 ms the next, when the numbers are the same?

BQN has two sorting primitives and two grading ones. ∧ (Sort Up) and ∨ (Sort Down) return the sorted array. ⍋ (Grade Up) and ⍒ (Grade Down) return the permutation that would sort it, as a list of indices. The language says nothing about algorithms. CBQN, the C implementation, picks one per call, and what it looks at first is the array’s storage type. This article reads src/builtins/grade.h at CBQN commit 2bf102f (2026-11-22) and checks it on an Apple M2 Pro.

The short version

  • CBQN stores a list of numbers packed, as bits, 1-, 2- or 4-byte integers, or 8-byte doubles. Literals and many primitive results get the narrowest type that fits every element. Anything else (a list of lists, a mix of numbers and characters) is a list of generic boxed values.
  • Sort on 1- and 2-byte integers ends in a counting sort once the list is long enough. On 4-byte integers it is an LSD radix sort, four passes.
  • Grade has to be stable, so it can’t use counting sort. It uses radix passes on 1- and 2-byte integers, and on 4-byte integers it first checks the range and uses a bucket sort when the range is small.
  • Short lists get insertion sort. Doubles and boxed values get Timsort.
  • The design notes recommend quicksort for the general case. CBQN has no quicksort yet, and grade.h lists one as a “SHOULD”.

Arrays have a storage type

BQN itself has one number type, the 64-bit float. CBQN stores a list written as a literal in the smallest type that fits it, and •internal.Type reports which:

T ← •internal.Type
•Show T¨ ⟨1‿2‿3, 1‿2‿300, 1‿2‿70000, 1‿2‿3.5, 0‿1‿1, "abc", ⟨1‿2, 3‿4⟩⟩

← defines a name, ‿ joins values into a list, ⟨…⟩ is a list of its comma-separated items, and T¨ applies T to each item (¨ is Each). •Show prints the result:

$ bqn types2.bqn
⟨ "i8arr" "i16arr" "i32arr" "f64arr" "bitarr" "c8arr" "harr" ⟩

300 needs two bytes, 70000 four, 3.5 a double. A list of 0s and 1s is stored as bits, a string as 1-byte characters, and the list of two lists is an harr, an array of generic values. In C every one of these is a different case of enum ElType (el_bit, el_i8, el_i16, el_i32, el_f64, the character types and el_B), and the sort functions switch on it.

The type comes from how an array was made, so it isn’t always the narrowest. •internal.Type 0.5×2‿4‿6 reports f64arr although the values are 1, 2 and 3, while 1+1‿2‿3 and 2×1‿2‿3 report i8arr. •internal.Squeeze converts an array to its most compact form.

The plan, from the source

grade.h opens with a comment that lists the whole strategy. The Sort and Grade part is:

// Sort and Grade
// Trivial results on empty, single-cell, or flagged-sorted 𝕩
//   COULD reverse to sort flat 𝕩 with flag in opposite direction
// Small ≠𝕩: insertion sort
// Long ≤2-byte sort (not grade): counting sort
//   Length threshold is around the type's maximum range
//   Count 1s for booleans
//   Large range/length ("sparse") uses scan: plus, or Singeli max/min
//   COULD range check 4-byte 𝕩 to try counting sort
// 4-byte grade checks range and sum (before even trying insertion sort)
//   If consistent with a permutation, grade as one and verify after
//   If small-range, grade with bucket sort
// Other 1-, 2-, 4-byte cases: radix sort
//   Singeli +` used if available, speeding up shorter cases
//   SHOULD skip steps where all bytes are equal
// General case: Timsort
// SHOULD scan for sortedness in all cases
// SHOULD use an adaptive quicksort for 4- and 8-byte arguments
// SHOULD widen odd cell sizes under 8 bytes in sort and grade

The file is included twice from sort.c, once with GRADE_UD(U,D) defined to pick the “Up” variant and once for “Down”, so ∧ and ∨ (and ⍋ and ⍒) are the same code with different comparisons.

Sort: the thresholds

For a list of n elements, Sort Up (and_c1) and Sort Down (or_c1) choose like this:

element type     n < A           A <= n < 256     n >= 256
bit              count the 1s and write 0s then 1s, for any n
i8, c8           insertion (16)  radix, 1 pass    counting sort
i16, c16         insertion (20)  radix, 2 passes  radix below 2^15 (2^18 for c16), else counting
i32, c32         insertion (32)  radix, 4 passes  radix, 4 passes
f64, boxed       Timsort, for any n

Before any of that, a list of length 0 or 1, or one already flagged as sorted in the same direction, is returned as it is. Sort sets that flag on its result, so sorting a sorted result again costs nothing (the second line of the output in “More measurements” below).

Counting sort

A counting sort counts how many times each possible value occurs and then writes each value out that many times. For 1-byte values the table has 256 entries; for 2-byte values, 65,536. The generic version in grade.h is short:

#define COUNTING_SORT(T) \
  usz C=1<<(8*sizeof(T));                              \
  TALLOC(usz, c0, C); usz *c0o=c0+C/2;                 \
  for (usz j=0; j<C; j++) c0[j]=0;                     \
  for (usz i=0; i<n; i++) c0o[xp[i]]++;                \
  ...

c0o points at the middle of the table so that negative values index below it. After counting, CBQN either loops over the table writing runs of equal values, or, when the table is large compared with n, writes each new value at the position where its run starts and fills the gaps with a max-scan (min-scan for ∨). That is the “sparse” case, and on this build it uses the Singeli scan.

input   2 0 2 1 2        counts   value 0: 1
                                  value 1: 1
                                  value 2: 3
output  0 1 2 2 2        (rebuilt from the counts; the input is not read again)

The BQN implementation notes call this “not-even-unstable”: the output values are reconstructed, so there is no link between an output element and an input one. That is fine for Sort, because equal numbers are interchangeable. It is useless for Grade, which has to say where each element came from.

Radix sort

From 32 elements up, Sort on 4-byte integers runs a least-significant-digit radix sort, four passes of one byte each. One pass over the input fills all four 256-entry count tables at once, a prefix sum turns counts into starting positions, and then each pass moves every element into the bucket for its next byte, alternating between the result array and a buffer. The top byte is read as signed ((i8)(v>>24)), so negative numbers land before positive ones.

Grade: the same idea, kept stable

The BQN specification requires a stable Grade: “a stable sorting algorithm must be used to implement Grade functions”, and equal elements are ordered by index in both directions. So ⍒ doesn’t reverse ⍋:

•Show ⍒ 1‿3‿3‿2‿3
•Show ⍋ 1‿3‿3‿2‿3
•Show ⌽ ⍒ 1‿3‿3‿2‿3

⍒ lists indices from the largest element down, ⍋ from the smallest up, and ⌽ reverses a list:

⟨ 1 2 4 3 0 ⟩
⟨ 0 3 1 2 4 ⟩
⟨ 0 3 4 2 1 ⟩

The three 3s sit at indices 1, 2 and 4, and both grades keep them in that order. The reversed Grade Down has them as 4 2 1.

Grade’s choices (gradeUp_c1, gradeDown_c1):

element type     short                    otherwise
bit              one pass writing positions of 0s and of 1s (grade_bool)
i8, c8           insertion, n < 24        radix, 1 pass (a bucket sort)
i16, c16         insertion, n < 48        radix, 2 passes
i32, c32         range check first:
                   range = n and the sum fits: try it as a permutation
                   range/2 < n: bucket sort over the range
                   else insertion (n < 64) or radix, 4 passes
f64, boxed       Timsort on (value, index) pairs

Every radix pass is a stable bucket sort, so the whole thing is stable without ever comparing two elements. The 4-byte permutation check sums the values and compares with the sum of the range; if it matches, it writes each index to the slot its value names and then checks that every slot got filled. A shuffled ↕n grades in one pass, about four times faster than random values (lines 3 and 4 below).

The result of Grade is also squeezed: a list of up to 128 indices comes back as i8arr, up to 32,768 as i16arr (the last lines of GRADE_CAT(c1)).

One million values, five storage types

Same values, different storage. This takes a million random integers below 100 and converts the array into each storage type with •internal.Variation, then times both primitives:

x ← 1e6 •rand.Range 100
Ms ← {•Repr (⌊0.5+100×1e3×𝕩)÷100}
{
  v ← 𝕩 •internal.Variation x
  •Out (•internal.Type v)∾"  ⍋ "∾(Ms 20 ⍋•_timed v)∾" ms   ∧ "∾(Ms 20 ∧•_timed v)∾" ms"
}¨ "Ai8"‿"Ai16"‿"Ai32"‿"Af64"‿"Ah"

1e6 •rand.Range 100 makes a million random integers from 0 to 99. Ms converts seconds to milliseconds, rounded to two decimals (⌊ is floor, ÷ divides, •Repr turns a number into text). The block {…}¨ runs once per variation name, with the name as 𝕩. 20 ⍋•_timed v calls ⍋ v 20 times and returns the average time in seconds. ∾ joins strings and •Out prints one.

$ bqn types.bqn
i8arr  ⍋ 0.96 ms   ∧ 0.49 ms
i16arr  ⍋ 4.67 ms   ∧ 0.39 ms
i32arr  ⍋ 0.82 ms   ∧ 8.21 ms
f64arr  ⍋ 76.84 ms   ∧ 70.34 ms
harr  ⍋ 75.76 ms   ∧ 70.54 ms

Each line matches a branch in the tables above. 1- and 2-byte Sort are counting sorts. 2-byte Grade runs two radix passes. 4-byte Grade sees a range of 100 and does a bucket sort, while 4-byte Sort, which has no range check, runs four radix passes. Doubles and boxed values go through Timsort and take 70 to 77 ms, against 0.4 to 8.2 ms for the packed integer paths.

More measurements

Ms ← {(•Repr (⌊0.5+100×1e3×𝕩)÷100)∾" ms"}
d ← 1e6 •rand.Range 1e9
b ← 100000 + 1e6 •rand.Range 100
s ← ∧ d
•Out "∧ d, random i32 below 1e9:    "∾Ms 10 ∧•_timed d
•Out "∧ on that sorted result:      "∾Ms 10 ∧•_timed s
•Out "⍋ d:                          "∾Ms 10 ⍋•_timed d
•Out "⍋ on a shuffled ↕1e6:         "∾Ms 10 ⍋•_timed •rand.Deal 1e6
•Out "∧ b, i32 from 1e5 to 1e5+99:  "∾Ms 10 ∧•_timed b
•Out "⍋⊸⊏ b:                        "∾Ms 10 ⍋⊸⊏•_timed b
•Show (∧b) ≡ ⍋⊸⊏ b

d is a million random integers below 10⁹ and b a million from 100,000 to 100,099 (+ adds 100,000 to each), both i32arr. •rand.Deal 1e6 is a random permutation of ↕1e6, the numbers 0 to 999,999. ⍋⊸⊏ b means (⍋ b) ⊏ b, which selects (⊏) the elements of b in grade order, so it sorts b. ≡ (Match) checks that it gives the same list as ∧ b.

$ bqn sort_extra.bqn
∧ d, random i32 below 1e9:    3.06 ms
∧ on that sorted result:      0 ms
⍋ d:                          4.17 ms
⍋ on a shuffled ↕1e6:         0.94 ms
∧ b, i32 from 1e5 to 1e5+99:  7.98 ms
⍋⊸⊏ b:                        1.58 ms
1

Timsort for everything else

Everything that isn’t a packed 1-, 2- or 4-byte type goes to the generic branch: f64 arrays, boxed arrays, lists of lists. For Sort, CBQN copies the elements into a plain array of values and runs tim_sort on it with BQN’s compare function. For Grade, generic_grade in sort.c builds an array of (value, index) pairs and Timsorts those.

The Timsort is not CBQN’s own. sortTemplate.h is “a modified version of” Christopher Swenson’s sort library, and one line in it shows why it was chosen:

#define SMALL_SORT BINARY_INSERTION_SORT // we need stable sorting!!

Grade must be stable, and Timsort is.

What the design notes suggest

The BQN repository has a long page on implementing sorting (implementation/primitive/sort.md). For simple data it suggests insertion sort for small sizes, counting sort for 1-byte types, and “branchless quicksorts” such as fluxsort for larger types, adding that radix sort “can be a lot faster” for 2- and 4-byte data. CBQN at 2bf102f follows the first two and the radix suggestion. A search of src/ for quicksort, pdq and flux finds one hit, the SHOULD use an adaptive quicksort for 4- and 8-byte arguments line in the comment above. Until that exists, a list of doubles gets the same Timsort as a list of lists.

Curious facts

  • Grade can beat Sort at sorting. On 4-byte integers with a small range, ⍋⊸⊏ (grade, then select by the grade) is faster than ∧, because Grade range-checks and Sort doesn’t. On the million i32 values from 100,000 to 100,099 above, ∧ took 7.98 ms and ⍋⊸⊏ 1.58 ms, for the same result.
  • Radix sort doesn’t skip constant bytes. In b the top two bytes are the same for every element, yet ∧ took 7.98 ms on b against 3.06 ms for random values below 10⁹ in the same run. The source lists the fix as a todo: “SHOULD skip steps where all bytes are equal”.
  • Characters sort as integers. c8, c16 and c32 arrays take the same branches as i8, i16 and i32. A ch flag mostly changes how the sign is treated, because character codes are unsigned; it also raises the 2-byte radix threshold.
  • A boolean sort is a popcount. Sorting a bit list counts its 1s and writes 0s followed by 1s, 64 at a time.
  • Whole numbers can still be doubles. 0.5×2‿4‿6 is stored as f64arr, so sorting it takes the Timsort branch even though every value is a small integer. •internal.Squeeze turns it back into i8arr.
  • Grade can return a 1-byte list. For up to 128 elements the indices come back as i8arr.

History

  • 2021-05-10: native ⍋ for i32 lists (CBQN commit 765098f4, dzaima).
  • 2021-09-09: Grade for i8 lists (12d5a5a8).
  • 2022-08-26 and 27: Marshall Lochbaum’s series “1-byte sorting: insertion, bucket, counting” (a0a4ecad), “2-byte sorting: insertion, radix, counting” (f946a3de), “4-byte sorting: insertion and radix” (9d59dff5) and “Radix grades” (e027aca0) set up most of the table above.
  • 2023-03-17: “Use AVX2 counting for 1-byte counting sort” (9d7d330a). At 2bf102f the 1-byte counting sort calls a Singeli simd_count_i8, which this arm64 build also has.

Sources

CBQN at commit 2bf102f:

BQN specification and docs at commit 5abbab9 (the one CBQN’s bundled compiler was built from):

Commits: 765098f4, 12d5a5a8, a0a4ecad, f946a3de, 9d59dff5, e027aca0, 9d7d330a.

ls bqn/