Help / Phrases / 6. A. Sorting

From J Wiki
Jump to navigation Jump to search


>> << Pri JfC LJ Phr Dic Voc !: Rel NuVoc wd Help Phrases


6A. Sorting

Sorting means the rearrangement of an array into an order based on some key, which may be either implicit or explicit. The implicit keys are the integer or real number fields, and the standard alphabet. Explicit keys may be any arbitrary set. Note that sorting applies equally well to character data and to Boolean, integer, real numbers, complex numbers, or to boxed data. When applied to real numbers, comparisons are exact. No tolerance is used. Verbs defined to sort in ascending order can be converted to give descending order by changing /: to \: , as in m0 and m1 . Note also that these verbs apply (unless they use the rank operator to prevent it) to arrays of arbitrary ranks, where the items are treated as if they were raveled.

m0=: /:~ Sort the array y in ascending order
m1=: \:~ Sort the array y in descending order
m2=: /:~"_1 Sort the items of array y ascending
d3=: /:@:{ { [ Sort indices x according to y
d4=: ]/:{"1 Sort table y according to column x
d5=: \:@[`(/:@[) @. ] Grade x up if y is 1 and down if y is 0
d6=: \:~@[`(/:~@[) @. ] Sort up or down (Try literal argument)
d7=: /:~ Sort y according to x
   y=:'leap','note',:'file'
   m1 y
note
leap
file

   m1"1 y
plea
tone
life

   z=:> ;: 'to be or not to be that is the question'
 
   (] ; m0 ; m1 ; m2) z
+-----------------------------------+
|to      |be      |to      |      ot|
|be      |be      |to      |      be|
|or      |is      |the     |      or|
|not     |not     |that    |     not|
|to      |or      |question|      ot|
|be      |question|or      |      be|
|that    |that    |not     |    ahtt|
|is      |the     |is      |      is|
|the     |to      |be      |     eht|
|question|to      |be      |einoqstu|
+-----------------------------------+

   q=: ?.15#9
   (] , m0 ,: m1) q
1 6 4 4 1 0 6 6 8 3 4 7 0 0 4
0 0 0 1 1 3 4 4 4 4 6 6 6 7 8
8 7 6 6 6 4 4 4 4 3 1 1 0 0 0

   x=: 2 3 4 5 0 1 9 8 7 6
   y=:100+10 4 8 6 7 9 5 3 2 1
   x ([ , ] ,: d3) y
  2   3   4   5   0   1   9   8   7   6
110 104 108 106 107 109 105 103 102 101
  9   8   7   1   6   3   4   2   5   0

   y=: ?.5 6$100
   d4=: ]/:{"1
   (0&d4 ; 2&d4 ; 5&d4) y
+-----------------------------------------------------+
| 3  5 52 67  0 38|13 75 45 53 21  4|13 75 45 53 21  4|
| 6 41 68 58 93 84| 3  5 52 67  0 38| 3  5 52 67  0 38|
|13 75 45 53 21  4|52  9 65 41 70 91|67 67 93 38 51 83|
|52  9 65 41 70 91| 6 41 68 58 93 84| 6 41 68 58 93 84|
|67 67 93 38 51 83|67 67 93 38 51 83|52  9 65 41 70 91|
+-----------------------------------------------------+

The random number generator ?. used here produces repeatable experiments, but ? can also be used. For example:

   ? 9 # 9
1 6 4 4 1 0 6 6 8
   ?. 9 # 9
3 8 8 4 2 0 2 7 4



>> << Pri JfC LJ Phr Dic Voc !: Rel NuVoc wd Help Phrases