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 bigger 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; }