Search code examples
sortingsmalltalkvisualworkssortedcollection

Smalltalk: Sort a collection by two criteria


How can I sort a collection by two criteria in Cincom VisualWorks?

Example: I have an OrderedCollection that contains persons, and want a new collection that sort the persons first by age, and then if the age is the same sort the persons by name.

Hope you can understand my english! Thanks..


Solution

  • Sean's code is fine, but I prefer it written this way, which is more intention-revealing and slightly more efficient:

    people sort: [ :a :b |
        a age < b age
            or: [a age = b age and: [ a name < b name ] ]
    

    The idea is that the sort block should answer true if item a sorts before item b. With two keys to consider, an item sorts before another item if either its primary key (age) is less, or the primary key is the same, and the secondary key (name) is less.

    This translate directly into the code above, and can be easily extended to a third or more sort criteria (e.g., either the secondary key is less, or it is the same and the tertiary key is less).