Welcome, guest | Sign In | My Account | Store | Cart

In a number of applications it is necessary to sort a list after several keys, for example first after a date and then after a name.

Tcl, 7 lines
1
2
3
4
5
6
7
set list {{12 11} {12 13} {12 12} {11 14} {13 12}}

    puts [lsort -index 1 $list]
    puts [lsort -index 0 [lsort -index 1 $list]]

{12 11} {12 12} {13 12} {12 13} {11 14}
{11 14} {12 11} {12 12} {12 13} {13 12}

There are currently two ways of doing this with the [lsort] command, the second much more efficient than the first. Both assume that the elements of the list to be sorted are lists themselves, containing both data and the keys to sort after.

Use the option -command and a custom comparison procedure.

Sort the list after the seecondary key first and then after the primary key. This makes use of the fact the [lsort] command is implemented using a mergesort algorithm, which is stable, i.e. preserves the order of previous sorts.

Created by Jeff Hobbs on Thu, 21 Jun 2001 (MIT)
Tcl recipes (162)
Jeff Hobbs's recipes (16)

Required Modules

  • (none specified)

Other Information and Tasks