in reply to Algorithm Pop Quiz: Sorting

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...

Replies are listed 'Best First'.
Re: Re: Algorithm Pop Quiz: Sorting
by RMGir (Prior) on Mar 25, 2002 at 11:18 UTC
    I like yours better, it's cleaner.
    --
    Mike