Anonymous user
Sorting algorithms/Counting sort: Difference between revisions
perl
(smalltalk) |
(perl) |
||
Line 198:
Sorted: 10 20 30 40 50 60 70 80
</pre>
=={{header|Perl}}==
<lang perl>#! /usr/bin/perl
use strict;
sub counting_sort
{
my ($a, $min, $max) = @_;
my @cnt = ();
my $range = $max - $min + 1;
foreach my $i ($min .. $max) { $cnt[$i] = 0 }
foreach my $n (@$a) { $cnt[$n]++ }
my $z = 0;
foreach my $i ($min .. $max) {
while( $cnt[$i]-- > 0) {
${$a}[$z] = $i;
$z++;
}
}
}</lang>
Testing:
<lang perl>my @ages = ();
push @ages, int(rand(140)) while(scalar(@ages) < 100);
counting_sort(\@ages, 0, 140);
print join("\n", @ages) . "\n";</lang>
=={{header|Smalltalk}}==
|