Crazy sort

Want to twist your brain by sorting in a stack language? Ok. First we need to define a function to put the minimum value on top:

[ dup 'm ; [ at dup m < [ 'm ; ] if [ , ] else ] len 1 - times m ] 
'min ;

Next we need a secondary stack to hold the intermediate sorted values. Let us create a child virtual machine to keep track of the secondary stack, so that it can respond to a get message and push the sorted values back to the main stack:

{ >> dup 'get equals [ <<< ] when } 
'sorted ;

We now have a function to find the minimum value on the stack and a virtual machine to keep track of the sorted elements, implementing the simple selection sort algorithm is just another one-liner:

[ [ , min dup sorted remove ] len 1 - times 'get sorted reverse , ]

'selsort ;

So there is our “stack sorter” in three lines!

Tests:

4 2 3 1 6 7 selsort .s
=> 1 2 3 5 6 7
20 100 45 selsort .s
=> 20 45 100 
1 2 3 4 5 selsort .s
=> 1 2 3 4 5