in reply to Re: My best attempt at sorting. Kindly suggest improvements/modifications.
in thread My best attempt at sorting. Kindly suggest improvements/modifications.
And just for fun, here's a simple implementatin of a mergesort:
sub mergesort { @_ < 2 and return @_; my @low = mergesort( @_[0 .. $#_ / 2] ); my @high = mergesort( @_[$#_ / 2 + 1 .. $#_] ); map !@high || @low && $low[0] <= $high[0] ? shift @low : shift @high +, 1..@_; }
Also, while looking at that simple quicksort, I realized it could be made stable by adding a third grep:
sub sqs # stable quicksort { @_ < 2 and return @_; my $p = $_[@_ / 2]; # pivot sqs( grep $_ < $p, @_ ), grep( $_ == $p, @_ ), sqs( grep $_ > $p, @_ + ); }
Or, if three passes over the input is just too much for you, it can be done with only one pass:
sub spsqs # single pass stable quicksort { @_ < 2 and return @_; my ($pivot, @items) = ($_[@_ / 2], [], [], []); push $items[$_ <=> $pivot]->@*, $_ for @_; spsqs($items[-1]->@*), $items[0]->@*, spsqs($items[1]->@*) }
( wondering if that's the first ever use of <=> in a subscript ? )
|
|---|