Sorting algorithms/Counting sort: Difference between revisions

Content added Content deleted
(Add Python)
(→‎{{header|Perl}}: Shortened.)
Line 344: Line 344:
{
{
my ($a, $min, $max) = @_;
my ($a, $min, $max) = @_;
my @cnt = ();
my @cnt = (0) x ($max - $min + 1);
$cnt[$_ - $min]++ foreach @$a;
my $range = $max - $min + 1;
foreach my $i ($min .. $max) { $cnt[$i] = 0 }
my $i = $min;
foreach my $n (@$a) { $cnt[$n]++ }
@$a = map {($i++) x $_} @cnt;

my $z = 0;
foreach my $i ($min .. $max) {
while( $cnt[$i]-- > 0) {
${$a}[$z] = $i;
$z++;
}
}
}</lang>
}</lang>


Testing:
Testing:


<lang perl>my @ages = ();
<lang perl>my @ages = map {int(rand(140))} 1 .. 100;
push @ages, int(rand(140)) while(scalar(@ages) < 100);

counting_sort(\@ages, 0, 140);
counting_sort(\@ages, 0, 140);
print join("\n", @ages) . "\n";</lang>
print join("\n", @ages), "\n";</lang>


=={{header|PHP}}==
=={{header|PHP}}==