And here's a Perl 5.16 implementation of quicksort...
use v5.16; my @sorted = (sub { return @_ unless @_ > 1; my $pivot = splice(@_, int(@_/2), 1); my (@small, @big); push @{ $_ < $pivot ? \@small : \@big }, $_ for @_; return (__SUB__->(@small), $pivot, __SUB__->(@big)) })->(@unsorted);
Can be made a little neater using List::MoreUtils...
use v5.16; use List::MoreUtils 'part'; my @sorted = (sub { return @_ unless @_ > 1; my $pivot = splice(@_, int(@_/2), 1); my ($small, $big) = part { $_ > $pivot } @_; return (__SUB__->(@$small), $pivot, __SUB__->(@$big)) })->(@unsorted);
In older Perls, without __SUB__ you can't recursively call a truly anonymous sub, so you need to have some kind of way of referring to the sub, such as assigning it to a lexical variable...
my @sorted = do { my $SUB; $SUB = sub { return @_ unless @_ > 1; my $pivot = splice(@_, int(@_/2), 1); my (@small, @big); push @{ $_ < $pivot ? \@small : \@big }, $_ for @_; return ($SUB->(@small), $pivot, $SUB->(@big)) }}->(@array);
In reply to Re^2: Numeric sorting WITHOUT <=>
by tobyink
in thread Numeric sorting WITHOUT <=>
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |