<<     >>

APL Exercises 8
Grade and Sort
 

⎕io←0 throughout.
 

8.0 Drills I

{(⊂⍋⍵)⌷⍵} sorts up any array that can be sorted and {(⊂⍒⍵)⌷⍵} sorts down. Currently some APL arrays can not be sorted (e.g. array of complex numbers).

Predict the result of each expression before evaluating it.

{(⊂⍋⍵)⌷⍵} 3 1 4 1 5 9
{(⊂⍋⍵)⌷⍵} 3 1 4 ¯1 5 9 9 9 9
{(⊂⍋⍵)⌷⍵} '3 1 4 1 5 9'
{(⊂⍋⍵)⌷⍵} 17?17
{(⊂⍋⍵)⌷⍵} ↑'three' 'one' 'four' 'one' 'five' 'nine'
{(⊂⍋⍵)⌷⍵} 5 2⍴3 1 4 1 5 9 2 6 5 3
 
{(⊂⍒⍵)⌷⍵} 3 1 4 1 5 9
{(⊂⍒⍵)⌷⍵} 3 1 4 ¯1 5 9 9 9 9
{(⊂⍒⍵)⌷⍵} '3 1 4 1 5 9'
{(⊂⍒⍵)⌷⍵} 17?17
{(⊂⍒⍵)⌷⍵} ↑'three' 'one' 'four' 'one' 'five' 'nine'
{(⊂⍒⍵)⌷⍵} 5 2⍴3 1 4 1 5 9 2 6 5 3

8.1 Sorting Without Using ⍋ ⍒

a. Write a function sortb b to sort a boolean vector b without using(or).

b. Write a function sorta a to sort a vector a of letters from the uppercase alphabet ⎕a without using(or).

c. Write a function sort1 s to sort a vector s of 1-byte integers (integers in the range ¯128+⍳256) without using(or).

In practice, you would useorto sort vectors from small domains. The above are for exercise only.
 

8.2 Quicksort

Quicksort on numeric vectors can be coded as follows:

   Q←{1≥≢⍵:⍵ ⋄ (∇(⍵<p)⌿⍵),((⍵=p)⌿⍵),(∇(⍵>p)⌿⍵) ⊣ p←⍵⌷⍨?≢⍵}
    
   Q 3 1 4 1 5 9 2 6 5 3 5 8 9 7 9
1 1 2 3 3 4 5 5 5 6 7 8 9 9 9

Explain in words what each part of the function does.

p←⍵⌷⍨?≢⍵ a randomly chosen “pivot”
∇(⍵<p)⌿⍵
 (⍵=p)⌿⍵
∇(⍵>p)⌿⍵

Derive Q1 from Q by removing the commas (thereby replacing catenation with stranding). Apply Q1 several times to the same argument.
 

8.3 Grade

APL does not have a primitive for sort but does have one for grade. A rationale for this arrangement is that you can use the result of grade to sort (re-order) something else, and of course to use the result of ⍋⍵ to sortitself. For example, you can useto sort a matrix which is not in the domain of .

   f←{⍵⌷⍨⊂?200⍴≢⍵}
   x←⍪f 'Curry' 'Durant' 'Thompson' 'Green' 'Iguodala'
   x,←f ↓?10 2⍴10
   x,←f ⎕a
   x,←f ?10⍴1000
   ⍴x
200 4
   5↑x

   ⍋x
DOMAIN ERROR
   ⍋x
  ∧

Write a function to sort the matrix x above. (Hint: useon the mix of each column to re-order the matrix, starting with the last column.)