Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Strange sort problem

Status
Not open for further replies.

marsd

IS-IT--Management
Apr 25, 2001
2,218
US
An insertion sort:

proc isort {arr {lvl "#0"}} {
upvar $lvl $arr loc

for {set i 1} {$i <= [array size loc]} {incr i} {
for {set x $i} {$x > 1 && $loc([expr $x - 1]) > $loc($x)} {incr $x -1} {
set val [expr $x - 1]
swap loc $val $x
}
}

return
}

The swap function is typical.

proc swap {arr el1 el2} {
upvar 1 $arr locswap

set sw $locswap($el1)
set locswap($el1) $locswap($el2)
set locswap($el2) $sw

return
}

With this array:
array set new {
1 23.45
2 3.12
3 16.2
4 56.78
5 900.1
6 123.45
7 iuuyt
8 ui
}

The insertion sort complains:
can't read &quot;2&quot;: no such variable

A qsort proc and bubble sort proc handle the whole thing nicely:

qsort new &quot;#0&quot; 1 [array size new] ; parray new
new(1) = 3.12
new(2) = 16.2
new(3) = 23.45
new(4) = 56.78
new(5) = 123.45
new(6) = 900.1
new(7) = iuuyt
new(8) = ui

Is there a way to get this to work? It is not critical
but it is puzzling.
 
The offending line is :
Code:
for {set x $i} {$x > 1 && $loc([expr $x - 1]) > $loc($x)} {incr $x -1} {

The first time that
Code:
incr $x - 1
is evaluated, x evals 2.
So, replacing $x by its value, Tcl reads
Code:
incr 2 - 1
and searches the variable 2 which is not defined.
You should rewrite this
Code:
incr x -1
and you will get:

1: 3.12
2: 16.2
3: 23.45
4: 56.78
5: 123.45
6: 900.1
7: iuuyt
8: ui

Good luck

ulis
 
Stupid, I should have seen that.

Thanks Ulis.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top