user
Task

Sort an array of integers (of any convenient size) into ascending order using Pancake sorting.

In short, instead of individual elements being sorted, the only operation allowed is to "flip" one end of the list, like so:

```
          Before:   6 7 8 9 2 5 3 4 1
          After:    9 8 7 6 2 5 3 4 1

```

Only one end of the list can be flipped; this should be the low end, but the high end is okay if it's easier to code or works better, but it **must** be the same end for the entire solution. (The end flipped can't be arbitrarily changed.)

Show both the initial, unsorted list and the final sorted list.

(Intermediate steps during sorting are optional.)

Optimizations are optional (but recommended).

Related tasks

* Number reversal game
* Topswops

Also see

* Wikipedia article:   pancake sorting.
assistant
(formerly Perl 6)

```
sub pancake_sort(@a is copy) {
    my $endpoint = @a.end;
    while $endpoint > 0 and not [<] @a {
        my $max_i = [0..$endpoint].max: { @a[$_] };
        my $max   = @a[$max_i];
        if @a[$endpoint] == $max {
            $endpoint-- while $endpoint >= 0 and @a[$endpoint] == $max;
            next;
        }
        # @a[$endpoint] is not $max, so it needs flipping;
        # Flip twice if max is not already at the top.
        @a[0..$max_i]    .= reverse if $max_i != 0;
        @a[0..$endpoint] .= reverse;
        $endpoint--;
    }
    return @a;
}

for <6 7 2 1 8 9 5 3 4>,
    <4 5 7 1 46 78 2 2 1 9 10>,
    <0 -9 -8 2 -7 8 6 -2 -8 3> -> @data {
   say 'input  = ' ~ @data;
   say 'output = ' ~ @data.&pancake_sort
}

```

Output:

```
input  = 6 7 2 1 8 9 5 3 4
output = 1 2 3 4 5 6 7 8 9
input  = 4 5 7 1 46 78 2 2 1 9 10
output = 1 1 2 2 4 5 7 9 10 46 78
input  = 0 -9 -8 2 -7 8 6 -2 -8 3
output = -9 -8 -8 -7 -2 0 2 3 6 8
```

The following is an alternative adapted from the code by Andrew Shitov.

```
# 20240908 Updated Raku programming solution

sub pancake-sort(@data is copy) { # imperative
   for @data.elems - 1 ... 1 {
      @data[0 .. @data[0..$_].maxpairs[*-1].key] .= reverse;
      @data[0 .. $_] .= reverse;
   }
   return @data
}

sub pancake_sort(@data is copy) { # recursive
   return @data if @data.elems <= 1;
   @data[0 .. @data.maxpairs[*-1].key] .= reverse;
   return pancake_sort(@data[1..*-1]).append: @data[0]
}

for <6 7 2 1 8 9 5 3 4>,
    <4 5 7 1 46 78 2 2 1 9 10>,
    <0 -9 -8 2 -7 8 6 -2 -8 3> -> @data {
   say 'input  = ' ~ @data;
   say 'output = ' ~ pancake-sort(@data);
   say 'output = ' ~ pancake_sort(@data) ~ "\n"
}

```

Output:

```
input  = 6 7 2 1 8 9 5 3 4
output = 1 2 3 4 5 6 7 8 9
output = 1 2 3 4 5 6 7 8 9

input  = 4 5 7 1 46 78 2 2 1 9 10
output = 1 1 2 2 4 5 7 9 10 46 78
output = 1 1 2 2 4 5 7 9 10 46 78

input  = 0 -9 -8 2 -7 8 6 -2 -8 3
output = -9 -8 -8 -7 -2 0 2 3 6 8
output = -9 -8 -8 -7 -2 0 2 3 6 8
```

You may Attempt This Online!