Skip to content

Commit cd70d43

Browse files
authored
Add Selection Sort in Tcl (#5081)
1 parent 82e54e7 commit cd70d43

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

archive/t/tcl/selection-sort.tcl

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
proc usage {} {
2+
puts stderr {Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"}
3+
exit 1
4+
}
5+
6+
proc parseList {s} {
7+
set tokens [split [string trim $s] ","]
8+
if {[llength $tokens] < 2} { usage }
9+
10+
set result {}
11+
12+
set result {}
13+
foreach token $tokens {
14+
set t [string trim $token]
15+
if {$t eq "" || [catch {expr {int($t)}} val]} usage
16+
lappend result $val
17+
}
18+
return $result
19+
}
20+
21+
proc isSorted {lst} {
22+
set prev [lindex $lst 0]
23+
foreach x [lrange $lst 1 end] {
24+
if {$x < $prev} {return 0}
25+
set prev $x
26+
}
27+
return 1
28+
}
29+
30+
proc selectionSort {lstVar} {
31+
upvar 1 $lstVar lst
32+
set n [llength $lst]
33+
34+
for {set i 0} {$i < $n - 1} {incr i} {
35+
set minIdx $i
36+
for {set j [expr {$i + 1}]} {$j < $n} {incr j} {
37+
if {[lindex $lst $j] < [lindex $lst $minIdx]} {
38+
set minIdx $j
39+
}
40+
}
41+
if {$minIdx != $i} {
42+
set temp [lindex $lst $i]
43+
lset lst $i [lindex $lst $minIdx]
44+
lset lst $minIdx $temp
45+
}
46+
}
47+
}
48+
49+
proc formatList {lst} { return [join $lst ", "] }
50+
51+
if {$argc != 1} { usage }
52+
53+
set numbers [parseList [lindex $argv 0]]
54+
55+
if {![isSorted $numbers]} {
56+
selectionSort numbers
57+
}
58+
59+
puts [formatList $numbers]

0 commit comments

Comments
 (0)