Sorting in Smalltalk
asSortedCollection orders; the sort block chooses how.
"asSortedCollection orders; a sort block chooses how."
| runs bySize |
runs := #(340 85 500 120).
Transcript show: runs asSortedCollection asArray printString; cr.
bySize := runs asSortedCollection: [:a :b | a > b].
Transcript show: 'Biggest first: ', bySize asArray printString; cr.
"sorted: works straight on sequenceable collections."
Transcript show: (#('folio' 'quarto' 'octavo')
sorted: [:a :b | a size < b size]) printString; cr.
Transcript show: (runs asSortedCollection: [:a :b | a > b])
first printString; cr.
How it works
asSortedCollectiondefaults to ascending.- A two-argument block like
[:a :b | a > b]flips it. sorted:works directly on arrays.
Keywords and builtins used here
TranscriptasArrayasSortedCollectioncrfirstprintStringsize
The run, in numbers
- Lines
- 14
- Characters to type
- 522
- Tokens
- 95
- Three-star pace
- 55 tpm
At the three-star pace of 55 tokens a minute, this run takes about 104 seconds.
Step 1 of 3 in Order & identity, step 21 of 31 in Language basics.