OK, here's the early-exit version. This proved more straight-forward than I was expecting. I was so sure that applying the knowledge of last-exchange would be difficult, I overlooked how trivial it actually is.

(This is still a bubble-sort, but it no longer is compelled to iterate [ $length - 1 ] times. Rather, the false-bottom can jump over several iterations if there is a clump of sorted elements at the end. Given the six-element sample list here, it saves only 3 iterations of the inner-loop, 17 versus 20 in my original.)

# Assume that rotate_up as defined in the original problem # statement has been defined. sub sordid { local $len = pop(@stack); local $bum = $len; local ($x, $y, $limit, $last_swap); while ($bum > 1) { $limit = $bum; $last_swap = 0; while (--$limit) { $x = pop(@stack); $y = pop(@stack); if ($x gt $y) { push(@stack, $x); push(@stack, $y); $last_swap = $bum - $limit; } else { push(@stack, $y); push(@stack, $x); } rotate_up($bum); } # At end of the $limit loop, top element is the max, and # top+1 to end is semi-sorted. One more rotate_up() # is needed before moving the floor up one notch. rotate_up($bum); $bum = $last_swap; } push(@stack, $len); } @stack = qw(d b f a e c 6); # <-- bottom .. top --> print "(@stack)\n"; # Prints: (d b f a e c 6) sordid(); print "(@stack)\n"; # Prints: (f e d c b a 6)

--rjray


In reply to Improved Bubble-Sort (Re: Re: Algorithm Pop Quiz: Sorting) by rjray
in thread Algorithm Pop Quiz: Sorting by clintp

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.