The meat of my solution (use strict, support subs, etc. not shown for brevity) is:
sub sort_stack { # How deep is the stack? my $depth = pop @stack; my $original_depth = $depth; # stacks with 0 or 1 elements already sorted while ($depth > 1) { # peek at top of stack, and assume it's the biggest item on there +until we determine otherwise my $top = pop @stack; push @stack, $top; my $biggest = $top; my $position = 0; # rotate through other stack elements to see if there are any bigg +er ones for my $rotations (1..$depth) { rotate_up($depth); $top = pop @stack; push @stack, $top; if ($top gt $biggest) { $biggest = $top; $position = $rotations; } } # rotate the biggest element into the bottom position for my $rotations (1..$position+1) { rotate_up($depth); } # now that the biggest element is at the bottom, reduce the depth +and sort the rest $depth--; } # put original stack depth back on top push @stack, $original_depth; }

Ugh, I took this challenge to heart and wrote this code without looking at any previous posts, but I now see it bears a striking similarity to the solution RMGir posted before me. Oh, well.

The thing that annoys me about this is that it looks like it's O(n^2). Is it possible to implement an O(nlogn) sort given the problem constraints? Hmmm, something to think about...


In reply to Re: Algorithm Pop Quiz: Sorting by seattlejohn
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.