Andrea Holstein wrote: > > "John W. Krahn" wrote: > > > That looks like a direct translation of algorithm 5.2.2B from TAoCP Vol. > > 3 however the usual implementation is more like Sedgewick's example: > > > > sub bubble { > > my $a = shift; > > > > for ( my $i = @$a; $i >= 1; $i-- ) { > > for ( my $j = 2; $j <= $i; $j++ ) { > > if ( $a->[ $j - 1 ] > $a->[ $j ] ) { > > $a->[ $j - 1, $j ] = $a->[ $j, $j - 1 ]; > > } > > } > > } > > } > > > Oh my dear, that's really unperlish :-)
That's because Sedgewick's book is titled _Algorithms in C_ > What do you think of: > > sub bubble { > my $a = shift; > my @a = @$a; You make a copy of the array, could be very expensive. > foreach my $i (reverse (1 .. @a)) { > foreach my $j (2 .. $i) { > ($a[$j-1], $a[$j]) = ($a[$j], $a[$j-1]) if $a[$j-1] > $a[$j]; > } > } > return $a; You return the reference to the original array (which hasn't been modified.) So basicly you sort a copy of an array and then throw it away. > } > > Note, that I changed the assignment, too, so now it should work :-) Yes, sorry, it should have been: @$a[ $j - 1, $j ] = @$a[ $j, $j - 1 ]; John -- use Perl; program fulfillment -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]