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 ? )


In reply to Re^2: My best attempt at sorting. Kindly suggest improvements/modifications. by tybalt89
in thread My best attempt at sorting. Kindly suggest improvements/modifications. by pritesh

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.