#source:http://blob.perl.org/tpc/1998/Perl_Language_and_Modules/Efficient%20Perl/handout.html
sub bubblesort {
my $self = shift ;
my ( $array ) = @_;
use integer; # More speed.
print "\@_ is @_ \n" ;
print "\$array is $array \n" ;
print "\$#$array is $#$array \n" ;
my $lastj = $#$array or return $array ; # 0 or 1 element array is sorted already just returned
my $firstj = 1;
my ( $i, $j, $keepj, $big );
# return $array if $firstj > $lastj; # 0 or 1 element array is sorted.
while ( $firstj ) {
# Run from
# ( $firstj - 1, $firstj ) .. ( $lastj - 1 , $lastj ),
# swapping when out of order.
for ( $j = $firstj, $i = $j - 1,
$keepj = $lastj, $firstj = 0;
$j <= $keepj;
$i = $j++ ) {
next unless $array->[ $i ] gt $array->[ $j ];
# Remember where we started if this is the first swap
# (but do not try to compare with the predecessor of 0)
$firstj = $firstj || $i || $j;
# Something to swap, try for a run of swaps.
# Remove the element that must swap up.
$big = splice @$array, $i, 1;
# Use $j < $keepj instead of $j <= $keepj
# because the array is one shorter right now.
# We already tested the $j entry that has been
# shifted to $j-1.
++$j while $j < $keepj && $array->[ $j ] lt $big;
# Put back the removed element in its new place.
splice @$array, $j, 0, $big;
# fix $j for the splice, and revalidate $i.
$i = $j++;
$lastj = $i;
}
}
return $array ;
} #eof sub
No comments:
Post a Comment
- the first minus - Comments have to be moderated because of the spammers
- the second minus - I am very lazy at moderating comments ... hardly find time ...
- the third minus - Short links are no good for security ...
- The REAL PLUS : Any critic and positive feedback is better than none, so your comments will be published sooner or later !!!!