Back Original

An APL a day! - Elimination Sort

I’ve started dabbling with APL. It has been a lot of fun solving the current batch of challenges. Archive. I loved how each challenge focuses on a small set of operators and makes us use them in various (devious!) combinations to solve the problems. I’m going through some of the older challenges to learn about more operators.

The past challenges can be found at APL Quest. Today, we’ll be solving the first problem from the 2023 challenge. Use tryapl.org as an online interactive REPL.

Elimination Sort

An “Elimination Sort” is a somewhat farcical sorting algorithm which starts with the leftmost element and keeps subsequent elements that are at least as large as the previous kept element, discarding all other elements. For example:

EliminationSort 1 3 7 3 5 8 5 8 1 6 1 8 1 10 8 4 3 4 1 4
1 3 7 8 8 8 10 

Write a function that:

Hint: The progressive-maxima idiomatic phrase ⌈, the greater or equal function ≥, and the replicate function / could be helpful in solving this problem.

Examples

      EliminationSort 10
1 2 3 4 5 6 7 8 9 10

      EliminationSort 2 1 4 3 6 5 8 7 10 9
2 4 6 8 10

      EliminationSort 1000 2500 1333 1969 3141 2345 3141 4291.9 4291.8 4292
1000 2500 3141 3141 4291.9 4292

      EliminationSort 1 3 7 3 5 8 5 8 1 6 1 8 1 10 8 4 3 4 1 4
1 3 7 8 8 8 10

Solution

See the solution
  • ⌈\⍵ to generate a scan of running maximum
    • e.g for ⌈\2 1 4 3 6 5 8 7 10 9 gives 2 2 4 4 6 6 8 8 10 10
  • Compare with ⍵ to only get those indices where the actual element exists
    • {(⍵=⌈\⍵)} 2 1 4 3 6 5 8 7 10 9 gives 1 0 1 0 1 0 1 0 1 0
  • Finally, replicate (/) to get only the required elements
    • {(⍵=⌈\⍵)/⍵} 2 1 4 3 6 5 8 7 10 9 gives 2 4 6 8 10