Perl Shellsort
In this tutorial, you will learn how shell sort is implemented in Perl.
#!/usr/bin/perl
sub shellsort {
my $array = shift;
my $i; # The initial index for the bubbling scan.
my $j; # The running index for the bubbling scan.
my $shell; # The shell size.
my $ncomp = 0; # The number of comparisons.
my $nswap = 0; # The number of swaps.
for ( $shell = 1; $shell < @$array; $shell = 2 * $shell + 1 ) {
# Do nothing here, just let the shell grow.
}
do {
$shell = int( ( $shell - 1 ) / 2 );
for ( $i = $shell; $i < @$array; $i++ ) {
for ( $j = $i - $shell;
$j >= 0 && ++$ncomp &&
$array->[ $j ] gt $array->[ $j + $shell ];
$j -= $shell ) {
@$array[ $j, $j + $shell ] = @$array[ $j + $shell, $j ];
$nswap++;
}
}
} while $shell > 1;
print "shellsort: ", scalar @$array,
" elements, $ncomp comparisons, $nswap swaps\n";
}
@array = qw(three good bands you've never heard of: spock's beard, gentle giant, chucklehead);
shellsort \@array;
print "@array\n";
Related Tutorials