Algorithm Search⌘K

Algorithmcore

Unicode collation algorithm

Also called UCA, multilevel collation.

Map strings to collation elements with primary, secondary and tertiary weights from a table such as the DUCET, then compare sort keys level by level. Tailorings adapt it to a language.

Time
O(n^2) worstΘ(n) best
Space
Θ(n) extra
Where
n = the length of the input in code points
Properties
deterministicofflineiterative

The Unicode collation algorithm (UCA) of Unicode Technical Standard 10 compares two strings in the order that people expect in a dictionary or a phone book, not in the order of their code points. Each string is first put in NFD by the normalization algorithm, then mapped to a sequence of collation elements. A collation element has a primary weight for the base letter, a secondary weight for accents and a tertiary weight for case and variants. The algorithm compares all the primary weights first, then the secondary weights, then the tertiary weights. The weights come from a table. The Default Unicode Collation Element Table (DUCET) is independent of language. A tailoring, for example from CLDR, changes the table for one language, such as Swedish, where "ä" sorts after "z".

In plain words

Sorting text by the numbers of its characters gives strange results. "Role" comes before "role" because capital letters have smaller numbers, and "rôle" goes after every word that starts with "ro" plus a plain letter. People compare words in steps. First they look only at the letters and ignore accents and case. Only if the letters are the same do they look at the accents. Only if the accents are the same too do they look at case.

The algorithm gives each character three numbers, one for each step. For a word, it lists all the first numbers, then all the second numbers, then all the third numbers, in one long key. Comparing two keys number by number then gives the order of the steps. Spaces and punctuation get special treatment, so that "de-luge" and "deluge" can sort together.

The problem

The input is two strings AA and BB, a collation element table TT and a variable weighting option. The output is −1-1, 00 or 11 for A<BA < B, A=BA = B and A>BA > B.

The table maps a sequence of one or more code points to a list of collation elements. In the allkeys.txt format of UTS 10 section 12.1, a line such as

0061  ; [.2380.0020.0002] # LATIN SMALL LETTER A

gives U+0061 LATIN SMALL LETTER A one element with the primary weight 2380, the secondary weight 0020 and the tertiary weight 0002, all in hexadecimal. A * instead of the . marks a variable element, which is used for spaces, punctuation and most symbols: U+0020 SPACE is [*0209.0020.0002]. A sequence of several code points on the left is a contraction, and several elements on the right are an expansion. For example U+00E6 LATIN SMALL LETTER AE has three elements, [.2380.0020.0004][.0000.011E.0004][.23E7.0020.0004], so it sorts with "ae" at the first level. An element with primary weight 0000 is ignorable at the first level. The weights in this page are copied from allkeys-16.0.0.txt.

UTS 10 Table 2 shows the levels. Here U+0022 stands in for the curly quotation marks of the table:

level difference example
L1 base letters role < roles < rule
L2 accents role < rôle < roles
L3 case and variants role < Role < rôle
L4 punctuation, with a variable option role < "role" < Role

The rows show that a difference at a lower level counts only if all higher levels are equal: rôle is after Role because the accent is a level 2 difference and the case a level 3 difference. Python's sorted() uses code point order and gives Role, role, rôle.

The algorithm

UTS 10 section 7 gives four steps: S1 normalize, S2 produce the collation element array, S3 form the sort key, S4 compare the sort keys.

  1. SORT-KEY(X, T, mode)
  2. 1X <- NFD(X) ▷ S1
  3. 2C <- []; i <- 0
  4. 3while i < |X| do
  5. 4j <- the largest end such that X[i..j-1] is a key of T, or i + 1 if there is none ▷ S2.1
  6. 5for each later non-starter c of X that is unblocked: if X[i..j-1] + c is a key of T, extend the match with c and remove c from X ▷ S2.1.1 to S2.1.3
  7. 6if the match S is a key of T then append T[S] to C else append IMPLICIT(X[i]) to C ▷ S2.2, S2.4
  8. 7i <- j ▷ S2.5
  9. 8W <- VARIABLE-WEIGHTING(C, mode) ▷ S2.3
  10. 9K <- []
  11. 10for level <- 1 to the number of levels do ▷ S3
  12. 11if level > 1 then append 0000 to K
  13. 12append the non-zero weights of this level of W to K, in order
  14. 13if level = 4 and mode = shift-trimmed then remove the trailing FFFF weights of this level
  15. 14return K
  16. COMPARE(A, B, T, mode)
  17. 15return the binary comparison of SORT-KEY(A, T, mode) and SORT-KEY(B, T, mode) ▷ S4

Longest match and discontiguous contractions (lines L4 and L5). A non-starter is a code point with a non-zero canonical combining class (ccc). A non-starter cc after the match is unblocked if no code point between the match and cc has ccc 0 or a ccc greater than or equal to the ccc of cc. Because the text is in NFD, the non-starters after a base are in canonical order, and line L5 can add a mark to a contraction even if another mark with a lower ccc stands between them.

Implicit weights (line L6). A code point that is not in the table gets two elements [.AAAA.0020.0002][.BBBB.0000.0000][.AAAA.0020.0002][.BBBB.0000.0000] (UTS 10 section 10.1.3, Table 16). For core Han ideographs, those with Unified_Ideograph=True in the blocks CJK Unified Ideographs and CJK Compatibility Ideographs, AAAA=FB40+(cp≫15)AAAA = \mathrm{FB40} + (cp \gg 15) and BBBB=(cp&7FFF)∣8000BBBB = (cp \mathbin{\&} \mathrm{7FFF}) \mathbin{|} \mathrm{8000}. Other Han ideographs use the base FB80, and any other code point the base FBC0. Tangut, Nushu and Khitan Small Script have their own bases FB00, FB01 and FB02. So U+4E00 gets [.FB40.0020.0002][.CE00.0000.0000], and Han ideographs sort in code point order after all letters of the table.

Variable weighting (line L8). UTS 10 section 4 gives four options for the variable elements:

  • Non-ignorable. Variable elements are used as they are. Spaces and punctuation then sort like letters, with low primary weights.
  • Blanked. Variable elements, and the primary ignorable elements that follow them, get all weights 0. Punctuation is then ignored.
  • Shifted. A fourth level is added, with the rules of Table 11: a variable element becomes [.0000.0000.0000.pppp][.0000.0000.0000.pppp] with its old primary weight at level 4; a primary ignorable element after a variable one becomes all zero; a completely ignorable element stays all zero; every other element gets FFFF at level 4.
  • Shift-Trimmed. As Shifted, but the trailing FFFF weights are removed from level 4.

Sort key (lines L9 to L13). The key holds the non-zero weights of level 1, the separator 0000, the non-zero weights of level 2, and so on. The separator 0000 is lower than any weight, so a shorter level wins as in a lexicographic order. Section 7.3 also allows a level to be backwards (step S3.6), which is used for French accents, and an identical level that appends the NFD string (step S3.10).

Example

The weights below are copied from allkeys-16.0.0.txt. With the non-ignorable option, rôle in NFD is U+0072 U+006F U+0302 U+006C U+0065, and step S2 gives

[.2584.0020.0002] [.252C.0020.0002] [.0000.0027.0002] [.24BC.0020.0002] [.23E7.0020.0002].[.2584.0020.0002]\,[.252C.0020.0002]\,[.0000.0027.0002]\,[.24BC.0020.0002]\,[.23E7.0020.0002].

The sort keys, with | for the separator 0000:

string sort key (non-ignorable)
role 2584 252C 24BC 23E7 | 0020 0020 0020 0020 | 0002 0002 0002 0002
Role 2584 252C 24BC 23E7 | 0020 0020 0020 0020 | 0008 0002 0002 0002
rôle 2584 252C 24BC 23E7 | 0020 0020 0027 0020 0020 | 0002 0002 0002 0002 0002

All three agree at level 1. At level 2, role and Role have 0020 at the third place, and rôle has 0027, so rôle is last. At level 3, Role has 0008 for the capital R and role has 0002, so role < Role < rôle.

The options give different orders of the strings of UTS 10 Table 12:

option order
non-ignorable de luge, de Luge, de-luge, de-Luge, death, deluge, deLuge, demark
shifted death, de luge, de-luge, deluge, de Luge, de-Luge, deLuge, demark
shift-trimmed death, deluge, de luge, de-luge, deLuge, de Luge, de-Luge, demark
blanked death, {de luge, de-luge, deluge}, {de Luge, de-Luge, deLuge}, demark

With the non-ignorable option, the space (primary 0209) and the hyphen (020D) sort before every letter, so all forms with a space or a hyphen come before death. With shifted, the level 4 key of de-luge is FFFF FFFF 020D FFFF FFFF FFFF FFFF and that of deluge is FFFF FFFF FFFF FFFF FFFF FFFF, so de-luge < deluge. With shift-trimmed, the key of deluge has an empty level 4 and comes first. In braces, blanked gives equal strings.

The L4 row of Table 2 needs care. With U+0022 QUOTATION MARK, the level 4 key of "role" under shifted is 033A FFFF FFFF FFFF FFFF 033A, which is lower than FFFF FFFF FFFF FFFF for role, so shifted gives "role" < role. The order role < "role" holds with shift-trimmed, where the level 4 key of role is empty.

Correctness

The claim is that COMPARE gives the order of UTS 10: first by the level 1 weights, then level 2, and so on. Each level of the sort key is the sequence of non-zero weights of that level, and two keys agree up to the separator of a level exactly when all earlier levels are equal. The separator 0000 is lower than any non-zero weight, so a level that is a proper prefix of the other ends first and is smaller. So binary comparison of the keys is the same as a comparison level by level. The proof is in proofs/correctness.md, together with the invariant of step S2. The tests check this equivalence on random strings for all four options, and check the order of a run of 19 lines of CollationTest_NON_IGNORABLE_SHORT.txt.

Proof: Binary comparison of UCA sort keys is the comparison level by level, and SORT-KEY terminatesfull

Setup. Let W=w1⋯wrW = w_1 \cdots w_r be the weight array after step S2.3, where each wjw_j has the weights wj(1),…,wj(k)w_j^{(1)}, \ldots, w_j^{(k)} for the kk levels of the option (k=3k = 3 for non-ignorable and blanked, k=4k = 4 for shifted and shift-trimmed). All weights are integers in [0,FFFF][0, \mathrm{FFFF}]. For a level ℓ\ell, let Pℓ(W)P_\ell(W) be the sequence of the non-zero weights wj(ℓ)w_j^{(\ell)} in the order of jj. For shift-trimmed, P4(W)P_4(W) also has its trailing FFFF weights removed. The UCA order compares P1P_1 of the two strings in lexicographic order, then P2P_2 if they are equal, and so on up to PkP_k. In lexicographic order a proper prefix is smaller.

Claim 1 (the key). Lines L9 to L14 return K(W)=P1(W) 0 P2(W) 0⋯0 Pk(W)K(W) = P_1(W)\,0\,P_2(W)\,0 \cdots 0\,P_k(W).

Proof. Invariant of the loop of line L10: before the iteration for level ℓ\ell, K=P1 0⋯0 Pℓ−1K = P_1\,0 \cdots 0\,P_{\ell-1} (empty for ℓ=1\ell = 1). Line L11 appends the separator if ℓ>1\ell > 1, line L12 appends the non-zero weights of level ℓ\ell in order, and line L13 removes trailing FFFF weights of level 4 for shift-trimmed. Line L13 only removes weights appended in the same iteration, because the separator 0 before them is not FFFF. So after the iteration K=P1 0⋯0 PℓK = P_1\,0 \cdots 0\,P_\ell. □\square

Claim 2. For two weight arrays WW and VV, the lexicographic comparison of K(W)K(W) and K(V)K(V) is equal to the comparison level by level.

Proof. Let ℓ\ell be the first level with Pℓ(W)≠Pℓ(V)P_\ell(W) \ne P_\ell(V). If there is none, the keys are equal and the comparison level by level gives equal too. Otherwise, the two keys have the same prefix P1 0⋯0P_1\,0 \cdots 0 up to the start of level ℓ\ell, of the same length. Compare p=Pℓ(W)p = P_\ell(W) and q=Pℓ(V)q = P_\ell(V) from that point.

  • If pp and qq differ at some place t≤min⁡(∣p∣,∣q∣)t \le \min(|p|, |q|), the keys differ first at the same place, with the same two weights, so both comparisons give the same answer.
  • If pp is a proper prefix of qq, then after pp the key K(W)K(W) has either the separator 0 (if ℓ<k\ell < k) or its end (if ℓ=k\ell = k). At the same place K(V)K(V) has the next weight of qq, which is non-zero by the definition of PℓP_\ell. So K(W)<K(V)K(W) < K(V), and p<qp < q in lexicographic order too. The case where qq is a proper prefix of pp is symmetric. □\square

This is the reason why the separator must be lower than every weight and why zero weights must be left out of the key: a 0 inside a level could be read as the end of the level.

Claim 3 (step S2). Lines L1 to L7 append, for each match of step S2.1, the elements of that match in the table, or the implicit weights of a code point with no match, in the order of the matches.

Proof. Invariant of the loop of line L3: CC holds the elements of the matches of X[0…i−1]X[0 \ldots i-1] in order, and every code point removed from XX by line L5 has been added to one of these matches. At line L4, jj is the end of the longest prefix of X[i…]X[i \ldots] that is a key of TT, which is the rule S2.1, or i+1i + 1 if no key starts at ii. Line L5 visits the non-starters after j−1j - 1 in order and stops at the first code point with ccc 0. It keeps the largest ccc bb of the non-starters that it skips. Because XX is in NFD, a non-starter cc is unblocked with respect to the match exactly when b<ccc(c)b < \mathrm{ccc}(c): a skipped code point with ccc at least ccc(c)\mathrm{ccc}(c) blocks it, and no starter lies in between. If the match plus cc is a key, line L5 extends the match and removes cc, as S2.1.3 says. Line L6 appends the elements of the match or the implicit weights (S2.2, S2.4), and line L7 moves to the code point after the contiguous part of the match (S2.5). The removed code points are later in XX, so the positions before jj do not change and the invariant holds. □\square

Claim 4 (variable weighting). VARIABLE-WEIGHTING follows Table 11 of UTS 10 for shifted, and the definitions of section 4 for the other options.

Proof. The implementation keeps a flag that is true when the last element with a non-zero primary weight was variable. For shifted, a variable element becomes (0,0,0,p)(0, 0, 0, p) and sets the flag; a completely ignorable element becomes (0,0,0,0)(0, 0, 0, 0); an element with primary 0 and the flag set becomes (0,0,0,0)(0, 0, 0, 0); any other element keeps its three weights and gets FFFF, and an element with a non-zero primary clears the flag. These are the five rows of Table 11. Blanked is the same with the fourth weight 0 and only three levels. Shift-trimmed is shifted with the trailing FFFF removed in line L13. Non-ignorable keeps all weights. □\square

Corollary. By Claims 1 to 4, COMPARE(AA, BB) returns the UCA order of AA and BB for the table TT and the option.

Termination. In each iteration of the loop of line L3, j≥i+1j \ge i + 1, so ii increases and the loop runs at most ∣X∣|X| times. The loop of line L5 either removes a code point from XX or increases its index, so it stops. The loops of lines L10 and L12 are over finite arrays.

Complexity

In the word-RAM model, a table lookup costs O(1)O(1), with a large constant: real tables have tens of thousands of entries, stored in a trie or a two-stage array. Let mm be the length of the longest contraction and ee the largest expansion, both constants of the table.

  • NFD. Linear in nn for text with short runs of combining marks.
  • Step S2. The longest match tries at most mm lengths at each start. The scan for discontiguous contractions walks over the run of non-starters after the match. On a run of kk non-starters this costs O(k)O(k) per start, so O(k2)O(k^2) in total, and O(n2)O(n^2) for a pathological string of one base and n−1n - 1 marks. On text in the Stream-Safe Text Format of UAX 15, which has at most 30 non-starters in a row, step S2 is Θ(n)\Theta(n).
  • Sort key. At most e⋅ne \cdot n elements and 4 weights each, so O(n)O(n) weights. Comparing two keys is linear in their length.
  • Space. Θ(n)\Theta(n) for the NFD string, the element array and the key.
case time
typical text, bounded runs of marks Θ(n)\Theta(n)
one base followed by n−1n - 1 marks O(n2)O(n^2)
compare two precomputed keys O(n)O(n)

Sorting NN strings costs O(Nlog⁡N)O(N \log N) comparisons. Building each key once and sorting the keys with a string sort such as MSD radix sort is usually faster than comparing strings directly.

Properties

  • Total preorder. COMPARE is reflexive and transitive, and any two strings are comparable. Different strings can be equal, for example under blanked, or "a" and a string with a completely ignorable code point. An identical level breaks such ties.
  • Canonical equivalence. Because of step S1, canonically equivalent strings get the same key: U+00E9 and U+0065 U+0301 sort as one string.
  • Not case folding. Case is only a level 3 difference. A comparison at strength 2 ignores case, but it is not the same as case folding: ß and ss are equal at level 1, but differ at level 2 in the DUCET, because ß has the extra element [.0000.011E.0004].
  • Language independent, then tailored. The DUCET gives one order for all scripts. No single order is right for all languages, so real systems use tailorings.
  • Not stable across versions. New characters and changes to the DUCET change the keys. Stored sort keys must be rebuilt when the table changes.

Variants and improvements

  • CLDR root collation and tailorings. CLDR (UTS 35 part 5) defines a root collation, which differs from the DUCET in a few places, and tailoring rules such as &z < å for each language. ICU implements this.
  • Parameters. CLDR adds options for strength, case first (uppercase before lowercase), backwards secondary weights, and numeric ordering of digit runs.
  • Incremental comparison. A comparison can stop at the first difference without building full keys. This is faster when strings differ early, and gives the same result.
  • ISO/IEC 14651. The international standard for the same ordering. The DUCET is kept aligned with its common template table.

When to use it

Use the UCA, or a library that implements it with CLDR data, whenever a list of strings is shown to people in sorted order: names, file lists, index entries. Use the language of the reader. Do not use it for keys of a data structure that only needs some fixed order: binary code point comparison is faster and stable across versions. For caseless matching, use case folding; for spoof detection, use confusable detection.

Pitfalls

  • Skipping NFD. Without step S1, U+00E9 and U+0065 U+0301 get different keys if the table has no entry for one of them. The test test_expansions_and_nfd compares their keys.
  • Comparing level by level per element. The keys compare all level 1 weights before any level 2 weight. Comparing elements one by one with all three weights at once gives rôle < Role, because the first elements differ at level 3.
  • Mixing options. Keys built with different variable options or table versions cannot be compared.
  • Assuming the L4 row of Table 2 under shifted. As the example shows, under shifted "role" < role.
  • Missing the discontiguous rule. A contraction with a mark can be split by another mark with a lower ccc. The test test_contractions_made_up_for_this_test has a case where U+0323 stands between the base and U+0301.
  • Tables of a different version. The weights and the implicit weight ranges in this page follow Unicode 16.0.0. Keys from another version of the table can give a different order.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

unicode_collation_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/unicode-collation-algorithm/. The authors are listed in prov/7HSE2K.jsonl.
"""The Unicode Collation Algorithm (UTS 10) with a subset of the DUCET.

The main algorithm of UTS 10 section 7: normalize to NFD (S1), map the string to
collation elements by longest match with discontiguous contractions (S2.1), synthesize
implicit weights for code points that are not in the table (S2.2, section 10.1.3),
apply variable weighting (S2.3, section 4), form a sort key (S3) and compare sort keys
in binary (S4).

The table below is a short subset of allkeys-16.0.0.txt (DUCET, Date: 2024-04-25).
The lines are copied verbatim. A code point that is not in the subset gets implicit
weights, so the results agree with the full DUCET only for strings over the code points
of the subset (after NFD).
"""

import unicodedata

ALLKEYS_LINES = """\
@version 16.0.0
0009  ; [*0201.0020.0002] # HORIZONTAL TABULATION (in ISO 6429)
000A  ; [*0202.0020.0002] # LINE FEED (in ISO 6429)
0020  ; [*0209.0020.0002] # SPACE
0021  ; [*0269.0020.0002] # EXCLAMATION MARK
0022  ; [*033A.0020.0002] # QUOTATION MARK
0027  ; [*0337.0020.0002] # APOSTROPHE
002D  ; [*020D.0020.0002] # HYPHEN-MINUS
005F  ; [*020B.0020.0002] # LOW LINE
0300  ; [.0000.0025.0002] # COMBINING GRAVE ACCENT
0301  ; [.0000.0024.0002] # COMBINING ACUTE ACCENT
0302  ; [.0000.0027.0002] # COMBINING CIRCUMFLEX ACCENT
0303  ; [.0000.002D.0002] # COMBINING TILDE
0306  ; [.0000.0026.0002] # COMBINING BREVE
0307  ; [.0000.002E.0002] # COMBINING DOT ABOVE
0308  ; [.0000.002B.0002] # COMBINING DIAERESIS
0309  ; [.0000.003B.0002] # COMBINING HOOK ABOVE
030A  ; [.0000.0029.0002] # COMBINING RING ABOVE
0323  ; [.0000.0042.0002] # COMBINING DOT BELOW
0327  ; [.0000.0030.0002] # COMBINING CEDILLA
0331  ; [.0000.0049.0002] # COMBINING MACRON BELOW
0332  ; [.0000.0021.0002] # COMBINING LOW LINE
0030  ; [.217D.0020.0002] # DIGIT ZERO
0031  ; [.217E.0020.0002] # DIGIT ONE
0032  ; [.217F.0020.0002] # DIGIT TWO
0033  ; [.2180.0020.0002] # DIGIT THREE
0034  ; [.2181.0020.0002] # DIGIT FOUR
0039  ; [.2186.0020.0002] # DIGIT NINE
0061  ; [.2380.0020.0002] # LATIN SMALL LETTER A
0041  ; [.2380.0020.0008] # LATIN CAPITAL LETTER A
00AA  ; [.2380.0020.0014] # FEMININE ORDINAL INDICATOR
00E6  ; [.2380.0020.0004][.0000.011E.0004][.23E7.0020.0004] # LATIN SMALL LETTER AE
00C6  ; [.2380.0020.000A][.0000.011E.0004][.23E7.0020.000A] # LATIN CAPITAL LETTER AE
0062  ; [.239A.0020.0002] # LATIN SMALL LETTER B
0042  ; [.239A.0020.0008] # LATIN CAPITAL LETTER B
0063  ; [.23B4.0020.0002] # LATIN SMALL LETTER C
0043  ; [.23B4.0020.0008] # LATIN CAPITAL LETTER C
0064  ; [.23CA.0020.0002] # LATIN SMALL LETTER D
0044  ; [.23CA.0020.0008] # LATIN CAPITAL LETTER D
0065  ; [.23E7.0020.0002] # LATIN SMALL LETTER E
0045  ; [.23E7.0020.0008] # LATIN CAPITAL LETTER E
0066  ; [.2422.0020.0002] # LATIN SMALL LETTER F
0046  ; [.2422.0020.0008] # LATIN CAPITAL LETTER F
0067  ; [.2431.0020.0002] # LATIN SMALL LETTER G
0047  ; [.2431.0020.0008] # LATIN CAPITAL LETTER G
0068  ; [.2458.0020.0002] # LATIN SMALL LETTER H
0048  ; [.2458.0020.0008] # LATIN CAPITAL LETTER H
0069  ; [.2473.0020.0002] # LATIN SMALL LETTER I
0049  ; [.2473.0020.0008] # LATIN CAPITAL LETTER I
0130  ; [.2473.0020.0008][.0000.002E.0002] # LATIN CAPITAL LETTER I WITH DOT ABOVE
0131  ; [.2477.0020.0002] # LATIN SMALL LETTER DOTLESS I
006A  ; [.248F.0020.0002] # LATIN SMALL LETTER J
004A  ; [.248F.0020.0008] # LATIN CAPITAL LETTER J
006B  ; [.24A8.0020.0002] # LATIN SMALL LETTER K
004B  ; [.24A8.0020.0008] # LATIN CAPITAL LETTER K
006C  ; [.24BC.0020.0002] # LATIN SMALL LETTER L
004C  ; [.24BC.0020.0008] # LATIN CAPITAL LETTER L
006D  ; [.24F6.0020.0002] # LATIN SMALL LETTER M
004D  ; [.24F6.0020.0008] # LATIN CAPITAL LETTER M
006E  ; [.2505.0020.0002] # LATIN SMALL LETTER N
004E  ; [.2505.0020.0008] # LATIN CAPITAL LETTER N
006F  ; [.252C.0020.0002] # LATIN SMALL LETTER O
004F  ; [.252C.0020.0008] # LATIN CAPITAL LETTER O
0070  ; [.255C.0020.0002] # LATIN SMALL LETTER P
0050  ; [.255C.0020.0008] # LATIN CAPITAL LETTER P
0071  ; [.2571.0020.0002] # LATIN SMALL LETTER Q
0051  ; [.2571.0020.0008] # LATIN CAPITAL LETTER Q
0072  ; [.2584.0020.0002] # LATIN SMALL LETTER R
0052  ; [.2584.0020.0008] # LATIN CAPITAL LETTER R
0073  ; [.25C6.0020.0002] # LATIN SMALL LETTER S
0053  ; [.25C6.0020.0008] # LATIN CAPITAL LETTER S
00DF  ; [.25C6.0020.0004][.0000.011E.0004][.25C6.0020.0004] # LATIN SMALL LETTER SHARP S
1E9E  ; [.25C6.0020.000A][.0000.011E.0004][.25C6.0020.000A] # LATIN CAPITAL LETTER SHARP S
0074  ; [.25F1.0020.0002] # LATIN SMALL LETTER T
0054  ; [.25F1.0020.0008] # LATIN CAPITAL LETTER T
0075  ; [.2614.0020.0002] # LATIN SMALL LETTER U
0055  ; [.2614.0020.0008] # LATIN CAPITAL LETTER U
0076  ; [.2644.0020.0002] # LATIN SMALL LETTER V
0056  ; [.2644.0020.0008] # LATIN CAPITAL LETTER V
0077  ; [.2656.0020.0002] # LATIN SMALL LETTER W
0057  ; [.2656.0020.0008] # LATIN CAPITAL LETTER W
0078  ; [.2660.0020.0002] # LATIN SMALL LETTER X
0058  ; [.2660.0020.0008] # LATIN CAPITAL LETTER X
0079  ; [.266C.0020.0002] # LATIN SMALL LETTER Y
0059  ; [.266C.0020.0008] # LATIN CAPITAL LETTER Y
007A  ; [.2682.0020.0002] # LATIN SMALL LETTER Z
005A  ; [.2682.0020.0008] # LATIN CAPITAL LETTER Z
"""

MODES = ("non-ignorable", "blanked", "shifted", "shift-trimmed")


def parse_allkeys(text: str) -> dict:
    """Parse lines in the allkeys.txt format (UTS 10 section 12.1).

    Return a dict from a tuple of code points (as str) to a list of collation elements.
    A collation element is a tuple (variable, primary, secondary, tertiary).
    """
    table = {}
    for line in text.splitlines():
        line = line.split("#", 1)[0].strip()
        if not line or line.startswith("@"):
            continue
        left, right = line.split(";", 1)
        key = tuple(chr(int(h, 16)) for h in left.split())
        ces = []
        for part in right.strip().lstrip("[").rstrip("]").split("]["):
            variable = part[0] == "*"
            p, s, t = (int(w, 16) for w in part[1:].split("."))
            ces.append((variable, p, s, t))
        table[key] = ces
    return table


DUCET_SUBSET = parse_allkeys(ALLKEYS_LINES)

# Core Han for implicit weights: Unified_Ideograph=True and Block=CJK_Unified_Ideographs
# or CJK_Compatibility_Ideographs (UTS 10 Table 16). Only these ranges are listed here.
_CORE_HAN = [(0x4E00, 0x9FFF)] + [(c, c) for c in (
    0xFA0E, 0xFA0F, 0xFA11, 0xFA13, 0xFA14, 0xFA1F, 0xFA21, 0xFA23, 0xFA24, 0xFA27, 0xFA28, 0xFA29)]
# Other Han: Unified_Ideograph=True in other blocks. Only extensions A and B are listed.
_OTHER_HAN = [(0x3400, 0x4DBF), (0x20000, 0x2A6DF)]


def _in(ranges, cp):
    return any(lo <= cp <= hi for lo, hi in ranges)


def implicit_weights(c: str) -> list:
    """Implicit weights [.AAAA.0020.0002][.BBBB.0000.0000] of section 10.1.3."""
    cp = ord(c)
    if _in(_CORE_HAN, cp):
        base = 0xFB40
    elif _in(_OTHER_HAN, cp):
        base = 0xFB80
    else:
        base = 0xFBC0
    return [(False, base + (cp >> 15), 0x0020, 0x0002), (False, (cp & 0x7FFF) | 0x8000, 0, 0)]


def collation_elements(s: str, table=None) -> list:
    """Steps S1 and S2.1, S2.2, S2.4, S2.5: the collation element array of s."""
    if table is None:
        table = DUCET_SUBSET
    longest = max(len(k) for k in table)
    x = list(unicodedata.normalize("NFD", s))  # @line L1
    ces = []
    i = 0  # @line L2
    while i < len(x):  # @line L3
        j = min(len(x), i + longest)  # @line L4
        while j > i + 1 and tuple(x[i:j]) not in table:
            j -= 1
        key = tuple(x[i:j])
        if key in table:
            k = j  # @line L5
            blocker = 0  # the largest ccc of a skipped non-starter
            while k < len(x):
                c = unicodedata.combining(x[k])
                if c == 0:
                    break
                if blocker < c and key + (x[k],) in table:
                    key = key + (x[k],)
                    del x[k]
                else:
                    blocker = max(blocker, c)
                    k += 1
            ces.extend(table[key])  # @line L6
        else:
            ces.extend(implicit_weights(x[i]))
        i = j  # @line L7
    return ces


def apply_variable_weighting(ces: list, mode: str) -> list:
    """Step S2.3 and section 4: return four-level weights (p, s, t, q)."""
    if mode not in MODES:
        raise ValueError(mode)
    out = []
    after_variable = False
    for variable, p, s, t in ces:
        if mode == "non-ignorable":
            out.append((p, s, t, 0))
        elif variable:
            after_variable = True
            out.append((0, 0, 0, p if mode != "blanked" else 0))
        elif p == 0 and s == 0 and t == 0:
            out.append((0, 0, 0, 0))
        elif p == 0 and after_variable:
            out.append((0, 0, 0, 0))
        else:
            if p != 0:
                after_variable = False
            out.append((p, s, t, 0xFFFF if mode != "blanked" else 0))
    return out


def sort_key(s: str, mode: str = "shifted", table=None) -> tuple:
    """Step S3: the sort key of s, a tuple of 16-bit weights with 0000 separators."""
    w = apply_variable_weighting(collation_elements(s, table), mode)  # @line L8
    levels = 3 if mode in ("non-ignorable", "blanked") else 4
    key = []  # @line L9
    for level in range(levels):  # @line L10
        if level > 0:  # @line L11
            key.append(0)
        part = [ce[level] for ce in w if ce[level] != 0]  # @line L12
        if level == 3 and mode == "shift-trimmed":  # @line L13
            while part and part[-1] == 0xFFFF:
                part.pop()
        key.extend(part)
    return tuple(key)  # @line L14


def compare(a: str, b: str, mode: str = "shifted", table=None) -> int:
    """Step S4: -1, 0 or 1 by binary comparison of the sort keys."""
    ka, kb = sort_key(a, mode, table), sort_key(b, mode, table)  # @line L15
    return (ka > kb) - (ka < kb)


def format_key(key: tuple) -> str:
    """Write a sort key as hexadecimal weights with | for the level separators."""
    return " ".join("|" if w == 0 else f"{w:04X}" for w in key)
test_unicode_collation_algorithm.py 168 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/unicode-collation-algorithm/. The authors are listed in prov/7HSE2K.jsonl.
# The NFD step uses unicodedata (unidata_version 16.0.0 with Python 3.14). The tests use
# only characters that are assigned in Unicode 3.2.
import random

from unicode_collation_algorithm import (DUCET_SUBSET, MODES, apply_variable_weighting,
                                         collation_elements, compare, format_key,
                                         implicit_weights, parse_allkeys, sort_key)

# 19 consecutive lines of CollationTest_NON_IGNORABLE_SHORT.txt 16.0.0
# (Date: 2024-08-14, 00:51:39 GMT), the lines that follow "1F170 0021".
COLLATION_TEST_RUN = """\
00E1 0021
00C1 0021
00E0 0021
00C0 0021
0103 0021
0102 0021
1EAF 0021
1EAE 0021
1EB1 0021
1EB0 0021
1EB5 0021
1EB4 0021
1EB3 0021
1EB2 0021
00E2 0021
00C2 0021
1EA5 0021
1EA4 0021
1EA7 0021
"""


def _text(line):
    return "".join(chr(int(h, 16)) for h in line.split())


def test_parse_allkeys_format():
    t = parse_allkeys("0020  ; [*0209.0020.0002] # SPACE\n"
                      "00E6  ; [.2380.0020.0004][.0000.011E.0004][.23E7.0020.0004] # AE\n")
    assert t[(" ",)] == [(True, 0x0209, 0x0020, 0x0002)]
    assert t[("æ",)] == [(False, 0x2380, 0x20, 4), (False, 0, 0x11E, 4), (False, 0x23E7, 0x20, 4)]
    assert DUCET_SUBSET[("a",)] == [(False, 0x2380, 0x0020, 0x0002)]
    assert DUCET_SUBSET[("A",)] == [(False, 0x2380, 0x0020, 0x0008)]


def test_collation_test_run():
    lines = [_text(x) for x in COLLATION_TEST_RUN.splitlines()]
    keys = [sort_key(x, "non-ignorable") for x in lines]
    for k1, k2 in zip(keys, keys[1:]):
        assert k1 < k2


def test_table_2_levels():
    assert compare("role", "roles") < 0 and compare("roles", "rule") < 0  # L1
    assert compare("role", "rôle") < 0 and compare("rôle", "roles") < 0  # L2
    assert compare("role", "Role") < 0 and compare("Role", "rôle") < 0  # L3
    # L4 with U+0022 for the quotation marks: this order holds with shift-trimmed.
    assert compare("role", '"role"', "shift-trimmed") < 0
    assert compare('"role"', "Role", "shift-trimmed") < 0
    # With shifted, the quotation mark weight 033A comes before FFFF at level 4.
    assert compare('"role"', "role", "shifted") < 0
    assert compare('"role"', "Role", "shifted") < 0


def test_python_sorted_is_code_point_order():
    words = ["rôle", "Role", "role"]
    assert sorted(words) == ["Role", "role", "rôle"]
    assert sorted(words, key=sort_key) == ["role", "Role", "rôle"]


TABLE_12 = ["de luge", "de Luge", "de-luge", "de-Luge", "death", "deluge", "deLuge", "demark"]


def test_table_12_variable_weighting():
    shuffled = TABLE_12[::-1]
    assert sorted(shuffled, key=lambda s: sort_key(s, "non-ignorable")) == [
        "de luge", "de Luge", "de-luge", "de-Luge", "death", "deluge", "deLuge", "demark"]
    assert sorted(shuffled, key=lambda s: sort_key(s, "shifted")) == [
        "death", "de luge", "de-luge", "deluge", "de Luge", "de-Luge", "deLuge", "demark"]
    assert sorted(shuffled, key=lambda s: sort_key(s, "shift-trimmed")) == [
        "death", "deluge", "de luge", "de-luge", "deLuge", "de Luge", "de-Luge", "demark"]
    k = {s: sort_key(s, "blanked") for s in TABLE_12}
    assert k["de luge"] == k["de-luge"] == k["deluge"]
    assert k["de Luge"] == k["de-Luge"] == k["deLuge"]
    assert k["death"] < k["deluge"] < k["deLuge"] < k["demark"]


def test_shifted_level_4_rules():
    # Table 11: variable, ignorable after a variable, primary ignorable, non-variable.
    ces = [(True, 0x0209, 0x20, 2), (False, 0, 0x25, 2), (False, 0x2380, 0x20, 8), (False, 0, 0x25, 2),
           (False, 0, 0, 0)]
    assert apply_variable_weighting(ces, "shifted") == [
        (0, 0, 0, 0x0209), (0, 0, 0, 0), (0x2380, 0x20, 8, 0xFFFF), (0, 0x25, 2, 0xFFFF), (0, 0, 0, 0)]
    assert apply_variable_weighting(ces, "blanked") == [
        (0, 0, 0, 0), (0, 0, 0, 0), (0x2380, 0x20, 8, 0), (0, 0x25, 2, 0), (0, 0, 0, 0)]


def _compare_by_levels(a, b, mode):
    """Level-by-level comparison of the weight arrays, without building a sort key."""
    wa = apply_variable_weighting(collation_elements(a), mode)
    wb = apply_variable_weighting(collation_elements(b), mode)
    for level in range(3 if mode in ("non-ignorable", "blanked") else 4):
        la = [w[level] for w in wa if w[level]]
        lb = [w[level] for w in wb if w[level]]
        if mode == "shift-trimmed" and level == 3:
            while la and la[-1] == 0xFFFF:
                la.pop()
            while lb and lb[-1] == 0xFFFF:
                lb.pop()
        if la != lb:
            return -1 if la < lb else 1
    return 0


def test_sort_key_agrees_with_level_comparison():
    rng = random.Random(1016)
    alphabet = "aAbBeEoéèôæß -'\"_!0"
    for _ in range(250):
        a = "".join(rng.choice(alphabet) for _ in range(rng.randint(0, 5)))
        b = "".join(rng.choice(alphabet) for _ in range(rng.randint(0, 5)))
        for mode in MODES:
            assert compare(a, b, mode) == _compare_by_levels(a, b, mode)


def test_order_is_total_and_consistent():
    rng = random.Random(77)
    alphabet = "abABáÁ -"
    words = ["".join(rng.choice(alphabet) for _ in range(rng.randint(1, 4))) for _ in range(150)]
    for mode in MODES:
        ordered = sorted(words, key=lambda s: sort_key(s, mode))
        for x, y in zip(ordered, ordered[1:]):
            assert compare(x, y, mode) <= 0


def test_implicit_weights():
    assert implicit_weights("一") == [(False, 0xFB40, 0x20, 2), (False, 0xCE00, 0, 0)]
    assert implicit_weights("㐀") == [(False, 0xFB80, 0x20, 2), (False, 0xB400, 0, 0)]
    assert compare("z", "一") < 0
    assert compare("一", "丁") < 0
    assert format_key(sort_key("一")) == "FB40 CE00 | 0020 | 0002 | FFFF FFFF"


def test_expansions_and_nfd():
    assert compare("æ", "ae") > 0 and compare("æ", "af") < 0
    assert sort_key("ß")[:2] == sort_key("ss")[:2]
    assert collation_elements("İ") == DUCET_SUBSET[("İ",)]
    assert sort_key("é") == sort_key("é")


def test_role_sort_key():
    assert format_key(sort_key("role")) == (
        "2584 252C 24BC 23E7 | 0020 0020 0020 0020 | 0002 0002 0002 0002 | FFFF FFFF FFFF FFFF")


def test_contractions_made_up_for_this_test():
    # A table made up for this test, with a contraction a + U+0301.
    table = parse_allkeys("0061 ; [.0100.0020.0002]\n0301 ; [.0000.0024.0002]\n"
                          "0302 ; [.0000.0027.0002]\n0323 ; [.0000.0042.0002]\n"
                          "0061 0301 ; [.0200.0020.0002]\n")
    assert collation_elements("á", table) == [(False, 0x200, 0x20, 2)]
    # Discontiguous: U+0323 (ccc 220) does not block U+0301 (ccc 230).
    assert collation_elements("ạ́", table) == [(False, 0x200, 0x20, 2), (False, 0, 0x42, 2)]
    # Blocked: U+0302 has the same ccc 230 as U+0301.
    assert collation_elements("ấ", table) == [
        (False, 0x100, 0x20, 2), (False, 0, 0x27, 2), (False, 0, 0x24, 2)]

History

UTS 10 gets a new revision with each version of the Unicode Standard, and the DUCET is updated in step. Revision 51, edited by Ken Whistler and Markus Scherer, is the version for Unicode 16.0.0. The ordering is kept aligned with ISO/IEC 14651. CLDR builds its root collation and its language tailorings on the UCA.

References

  1. Ken Whistler and Markus Scherer (editors), Unicode Technical Standard 10, Unicode Collation Algorithm, revision 51, 2024-08-22, Section 1.1 (Table 2, Comparison Levels), Section 4 and 4.1 (Variable Weighting, Table 11 and Table 12), Section 7 (Main Algorithm, steps S1 to S4), Section 10.1.3 (Implicit Weights, Table 16) and Section 12.1 (Allkeys File Format)
  2. allkeys-16.0.0.txt, the Default Unicode Collation Element Table (DUCET), 2024-04-25, the data lines, in the format of UTS 10 section 12.1
  3. CollationTest 16.0.0 (CollationTest_NON_IGNORABLE and CollationTest_SHIFTED, with _SHORT variants), the lines of CollationTest_NON_IGNORABLE_SHORT.txt, which are in increasing order
  4. Unicode Technical Standard 35, Unicode Locale Data Markup Language (LDML), Part 5: Collation, the CLDR root collation and the syntax of tailoring rules

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example