TCL Sort program without using lsort [closed]

While we won’t give you the answer, we can suggest a few useful things. For example, you compare two elements of a list (at $idx1 and $idx2) with this:

string compare [lindex $theList $idx1] [lindex $theList $idx2]

And you might use this procedure to swap those two elements:

proc swap {nameOfListVar idx1 idx2} {
    upvar 1 $nameOfListVar theList
    set tmp [lindex $theList $idx1]
    lset theList $idx1 [lindex $theList $idx2]
    lset theList $idx2 $tmp
    return
}

Which you’d call like:

# Pass the list variable *name*
swap theList $idx1 $idx2

Generally, you can do a sorting algorithm like this:

  • While the list is not sorted,
    • find a pair of elements in the wrong order and swap them.

Everything else is optimization. (Bear in mind that real Tcl programs just use lsort because it implements an efficient algorithm with many good properties, and the rest either don’t need sorting or delegate the problem to a database engine…)

Leave a Comment