⍋ ⍒

Grade (, ) is a pair of ambivalent primitive functions related to sorting. Instead of sorting the given array directly, Grade returns a permutation vector whose length equals the number of major cells, so that indexing into the argument gives the sorted array. The glyph is called Grade Up and gives the ascending sort order, while is called Grade Down and gives the descending sort order.

Monadic Grade returns the sorting order of the major cells of the argument. Indexing into the original argument gives the sorted array; indexing into another array gives the result commonly known as Sort By.

A'foo' 'bar' 'baz'  ⍝ A character matrix
foo
bar
baz
A  ⍝ Grade up its rows
2 3 1
A[A;]  ⍝ Move the rows to sorted order (ascending)
bar
baz
foo
A  ⍝ Grade down its rows
1 3 2
A[A;]  ⍝ Move the rows to sorted order (descending)
foo
baz
bar
B15 10 5
A[B;]  ⍝ Sort A by B
baz
bar
foo

Grade performs stable sorting, so that the indices of the repeated major cells are sorted by the order of appearance. Because of this, Grade Down produces the reverse of Grade Up only if all the major cells are unique.

S6 10 10 3 2 15  TS,¨6
⍝ Note that the order of two 10s are preserved in both cases
(S) (T[S])
┌───────────┬────────────────────────────┐
5 4 1 2 3 6│┌───┬───┬───┬────┬────┬────┐│
││2 53 46 110 210 315 6││
│└───┴───┴───┴────┴────┴────┘│
└───────────┴────────────────────────────┘
(S) (T[S])
┌───────────┬────────────────────────────┐
6 2 3 1 4 5│┌────┬────┬────┬───┬───┬───┐│
││15 610 210 36 13 42 5││
│└────┴────┴────┴───┴───┴───┘│
└───────────┴────────────────────────────┘

Dyalog APL supports total array ordering when comparing nested arrays of possibly different shape and type. Grade is the only built-in function which can perform comparisons between arbitrary arrays of previously unknown order (Interval Index requires the left argument to be sorted beforehand).

A(1(2 3)) (1 3) (0 1 2)
┌─────┬───┬───────┐
│┌─┬─┐│1 3│┌─────┐│
││12││   ││0 1 2││
││ 3││   │└─────┘│
│└─┴─┘│
└─────┴───┴───────┘
A
3 1 2
Works in: Dyalog APL

Dyadic Grade is limited to simple character array arguments. The left argument specifies the collation order to use when sorting the right argument.

If the left argument is a vector, the sorting order is simply the order of appearance in the left argument. In other words, XY equals XY, and same for .

⎕A'ZAM,.BIA'  ⍝ Alphabetical order, garbage goes last
2 8 6 7 3 1 4 5
(⎕A)'ZAM,.BIA'  ⍝ Reverse alphabetical order, garbage still goes last
1 3 7 6 2 8 4 5

If the left argument is a higher-rank array, sorting is done in multiple stages. The last axis of X takes highest precedence, then the next-to-last, and so on, giving ties to all characters that appear at the same index over the current axis. A notable application is case-insensitive sorting.

Data
ABLE
aBLE
ACRE
ABEL
aBEL
ACES
Coll
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
CollData
4 5 1 2 6 3
Data[CollData;]
ABEL
aBEL
ABLE
aBLE
ACES
ACRE