Since Capytalk is a functional language without loop structures, you have to think of sorting in a different way than you would in a language like C or Smalltalk. Each element in the sorted Array is going to be a Capytalk expression describing which EventValues have values less than the value in this slot, and which EventValues have a value greater than the one in this slot.

If you write it all out explicitly, then each expression in the Array gets longer than the one in the previous position. This can get messy quickly, so here's some Smalltalk to construct the Array of Capytalk expressions:

| eventValues sortedArray min max leftIndex rightIndex infinity minusInfinity prevMin prevMax |

eventValues := {!P copies: 5}.

sortedArray := Array new: eventValues size.

"Set min and max to values that can never be found in your eventValues."

infinity := 8000.

minusInfinity := -8000.

prevMin := minusInfinity.

prevMax := infinity.

"Construct an expression that puts the minimum at the leftmost index and maximum at the rightmost index. Keep track of min and max as you move the leftIndex to the right and rightIndex to the left until you meet in the middle."

leftIndex := 1.

rightIndex := eventValues size.

[leftIndex <= rightIndex] whileTrue: [

min := infinity.

max := minusInfinity.

1 to: eventValues size do: [ :i | | p |

p := eventValues at: i.

"If p has already been sorted, use infinity or minusInfinity in its place, effectively removing it from the computation of the min or max."

min := ((p gt: prevMin) true: (p) false: (infinity)) vmin: min.

max := ((p lt: prevMax) true: (p) false: (minusInfinity)) vmax: max].

sortedArray at: leftIndex put: min.

sortedArray at: rightIndex put: max.

prevMin := min.

prevMax := max.

leftIndex := leftIndex + 1.

rightIndex := rightIndex - 1].

sortedArray

And here's a Sound that uses this code to create a sorted array of ascending pitches for an AnalogSequencer. It captures !KeyNumbers using sampleAndHold on !KeyDown (you can use the Fake Keyboard from the Tools menu to enter them if you don't have a keyboard). No matter what order you play the pitches, the sequencer plays them in sorted or ascending order.

The first Sound displays the captured values as !Ps and the sorted values as !Qs. In the second Sound, the Smalltalk to create the sorting Capytalk Array is pasted directly into the KeyPitches parameter field.