in reply to Re: Numeric sorting WITHOUT <=>
in thread Numeric sorting WITHOUT <=>
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);
perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^3: Numeric sorting WITHOUT <=>
by ikegami (Patriarch) on Oct 10, 2012 at 18:25 UTC | |
by tobyink (Canon) on Oct 10, 2012 at 21:43 UTC | |
by ikegami (Patriarch) on Oct 10, 2012 at 22:24 UTC |
In Section
Seekers of Perl Wisdom