5人の学生を 身長で ソート (構造体)
明解C言語 入門編 > 12. 構造体 >
5人の学生を 身長で ソート (構造体)
Perl
$NINSU = 5; sub swap { my ($x, $y) = @_; $tmp = $$x; $$x = $$y; $$y = $tmp; } sub sort { my ($data, $n) = @_; $k = $$n - 1; while ($k >= 0) { $j = -1; foreach $i(1..$k) { if ($$data[$i - 1]{"height"} > $$data[$i]{"height"}) { $j = $i - 1; &swap(\$$data[$i], \$$data[$j]); } } $k = $j; } } @data = ( {name => "Sato", height => 178, weight => 61.0}, {name => "Sanaka", height => 175, weight => 60.5}, {name => "Takao", height => 173, weight => 80.0}, {name => "Mike", height => 165, weight => 72.0}, {name => "Masaki", height => 179, weight => 77.5} ); print "ソート前:\n"; for (0..$NINSU-1) { printf("%2d:%-8s%4d\n", $_ + 1, $data[$_]{"name"}, $data[$_]{"height"}); } print "\n"; &sort(\@data, \$NINSU); print "ソート後:\n"; for (0..$NINSU-1) { printf("%2d:%-8s%4d\n", $_ + 1, $data[$_]{"name"}, $data[$_]{"height"}); }
実行結果
L:\>perl lesson_12_096.pl
メ[ト前:
1:Sato 178
2:Sanaka 175
3:Takao 173
4:Mike 165
5:Masaki 179メ[ト後:
1:Mike 165
2:Takao 173
3:Sanaka 175
4:Sato 178
5:Masaki 179