Sorting algorithms/Pancake sort: Difference between revisions

m
m (→‎{{header|Wren}}: Minor tidy)
 
(41 intermediate revisions by 23 users not shown)
Line 1:
{{task|Sorting Algorithms}}
[[Category:Sorting]]
{{Sorting Algorithm}}
 
Line 6 ⟶ 7:
 
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
Before:
After: '''6 79 8 97 6''' 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).
 
(Intermediate steps during sorting are optional.)
For more information on pancake sorting, see [[wp:Pancake sorting|the Wikipedia entry]].
 
Optimizations are optional (but recommended).
See also:
 
* [[Number reversal game]]
 
* [[Topswops]]
;Related tasks:
*   [[Number reversal game]]
*   [[Topswops]]
 
 
;Also see:
*   Wikipedia article:   [[wp:Pancake sorting|pancake sorting]].
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V tutor = 1B
 
F pancakesort(&data)
I data.len <= 1
R
I :tutor
print()
L(size) (data.len .< 1).step(-1)
V maxindex = max(0 .< size, key' x -> @data[x])
I maxindex + 1 != size
I maxindex != 0
I :tutor
print(‘With: #. doflip #.’.format(data.map(x -> String(x)).join(‘ ’), maxindex + 1))
data.reverse_range(0 .< maxindex + 1)
I :tutor
print(‘With: #. doflip #.’.format(data.map(x -> String(x)).join(‘ ’), size))
data.reverse_range(0 .< size)
I :tutor
print()
 
V data = ‘6 7 2 1 8 9 5 3 4’.split(‘ ’)
print(‘Original List: ’data.join(‘ ’))
pancakesort(&data)
print(‘Pancake Sorted List: ’data.join(‘ ’))</syntaxhighlight>
 
{{out}}
<pre>
Original List: 6 7 2 1 8 9 5 3 4
 
With: 6 7 2 1 8 9 5 3 4 doflip 6
With: 9 8 1 2 7 6 5 3 4 doflip 9
With: 4 3 5 6 7 2 1 8 9 doflip 5
With: 7 6 5 3 4 2 1 8 9 doflip 7
With: 1 2 4 3 5 6 7 8 9 doflip 3
With: 4 2 1 3 5 6 7 8 9 doflip 4
With: 3 1 2 4 5 6 7 8 9 doflip 3
With: 2 1 3 4 5 6 7 8 9 doflip 2
 
Pancake Sorted List: 1 2 3 4 5 6 7 8 9
</pre>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program mergeSort64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeConstantesARM64.inc"
 
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessSortOk: .asciz "Table sorted.\n"
szMessSortNok: .asciz "Table not sorted !!!!!.\n"
sMessResult: .asciz "Value : @ \n"
sMessCounter: .asciz "sorted in @ flips \n"
szCarriageReturn: .asciz "\n"
.align 4
TableNumber: .quad 1,3,11,6,2,-5,9,10,8,4,7
#TableNumber: .quad 10,9,8,7,6,-5,4,3,2,1
.equ NBELEMENTS, (. - TableNumber) / 8
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrTableNumber // address number table
mov x1,0 // first element
mov x2,NBELEMENTS // number of élements
bl pancakeSort
ldr x0,qAdrTableNumber // address number table
bl displayTable
mov x0,x10 // display counter
ldr x1,qAdrsZoneConv
bl conversion10S // décimal conversion
ldr x0,qAdrsMessCounter
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
ldr x0,qAdrTableNumber // address number table
mov x1,NBELEMENTS // number of élements
bl isSorted // control sort
cmp x0,1 // sorted ?
beq 1f
ldr x0,qAdrszMessSortNok // no !! error sort
bl affichageMess
b 100f
1: // yes
ldr x0,qAdrszMessSortOk
bl affichageMess
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrsZoneConv: .quad sZoneConv
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsMessResult: .quad sMessResult
qAdrTableNumber: .quad TableNumber
qAdrszMessSortOk: .quad szMessSortOk
qAdrszMessSortNok: .quad szMessSortNok
qAdrsMessCounter: .quad sMessCounter
/******************************************************************/
/* control sorted table */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the number of elements > 0 */
/* x0 return 0 if not sorted 1 if sorted */
isSorted:
stp x2,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
mov x2,0
ldr x4,[x0,x2,lsl 3]
1:
add x2,x2,1
cmp x2,x1
bge 99f
ldr x3,[x0,x2, lsl 3]
cmp x3,x4
blt 98f
mov x4,x3
b 1b
98:
mov x0,0 // not sorted
b 100f
99:
mov x0,1 // sorted
100:
ldp x3,x4,[sp],16 // restaur 2 registers
ldp x2,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* flip */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains first start index
/* x2 contains the number of elements */
/* x3 contains the position of flip */
flip:
//push {r1-r6,lr} // save registers
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
str x6, [sp,-16]! // save registers
add x10,x10,#1 // flips counter
cmp x3,x2
sub x4,x2,1
csel x3,x4,x3,ge // last index if position >= size
1:
cmp x1,x3
bge 100f
ldr x5,[x0,x1,lsl 3] // load value first index
ldr x6,[x0,x3,lsl 3] // load value position index
str x6,[x0,x1,lsl 3] // inversion
str x5,[x0,x3,lsl 3] //
sub x3,x3,1
add x1,x1,1
b 1b
100:
ldr x6, [sp],16 // restaur 1 register
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* pancake sort */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains first start index
/* x2 contains the number of elements */
pancakeSort:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
stp x8,x9,[sp,-16]! // save registers
sub x7,x2,1 // last index
1:
mov x5,x1 // index
mov x4,0 // max
mov x3,0 // position
mov x8,1 // top sorted
ldr x9,[x0,x5,lsl 3] // load value A[i-1]
2:
ldr x6,[x0,x5,lsl 3] // load value
cmp x6,x4 // compare max
csel x4,x6,x4,ge // max = A[i}
csel x3,x5,x3,ge // position = index
cmp x6,x9 // cmp A[i] A[i-1] sorted ?
csel x8,xzr,x8,lt // no
mov x9,x6 // A[i-1] = A[i]
add x5,x5,1 // increment index
cmp x5,x7 // end ?
ble 2b
cmp x8,1 // sorted ?
beq 100f // yes -> end
cmp x3,x7 // position ok ?
beq 4f // yes
cmp x3,0 // first position ?
beq 3f
bl flip // flip if not greather in first position
3:
mov x3,x7 // and flip the whole stack
bl flip
4:
//bl displayTable // to display an intermediate state
subs x7,x7,1 // decrement number of pancake
bge 1b // and loop
100:
ldp x8,x9,[sp],16 // restaur 2 registers
ldp x6,x7,[sp],16 // restaur 2 registers
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
 
/******************************************************************/
/* Display table elements */
/******************************************************************/
/* x0 contains the address of table */
displayTable:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x2,x0 // table address
mov x3,0
1: // loop display table
ldr x0,[x2,x3,lsl 3]
ldr x1,qAdrsZoneConv
bl conversion10S // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
add x3,x3,1
cmp x3,NBELEMENTS - 1
ble 1b
ldr x0,qAdrszCarriageReturn
bl affichageMess
mov x0,x2
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
<pre>
Value : -5
Value : +1
Value : +2
Value : +3
Value : +4
Value : +6
Value : +7
Value : +8
Value : +9
Value : +10
Value : +11
 
sorted in +17 flips
Table sorted.
</pre>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC PrintArray(INT ARRAY a INT size)
INT i
 
Put('[)
FOR i=0 TO size-1
DO
IF i>0 THEN Put(' ) FI
PrintI(a(i))
OD
Put(']) PutE()
RETURN
 
PROC Flip(INT ARRAY a INT last)
INT i,n,tmp
 
n=(last-1)/2
FOR i=0 TO n
DO
tmp=a(i)
a(i)=a(last-i)
a(last-i)=tmp
OD
RETURN
 
PROC PancakeSort(INT ARRAY a INT size)
INT i,j,maxpos
 
i=size-1
WHILE i>=0
DO
maxpos=i
FOR j=0 TO i-1
DO
IF a(j)>a(maxpos) THEN
maxpos=j
FI
OD
 
IF maxpos#i THEN
IF maxpos#0 THEN
Flip(a,maxpos)
FI
Flip(a,i)
FI
i==-1
OD
RETURN
 
PROC Test(INT ARRAY a INT size)
PrintE("Array before sort:")
PrintArray(a,size)
PancakeSort(a,size)
PrintE("Array after sort:")
PrintArray(a,size)
PutE()
RETURN
 
PROC Main()
INT ARRAY
a(10)=[1 4 65535 0 3 7 4 8 20 65530],
b(21)=[10 9 8 7 6 5 4 3 2 1 0
65535 65534 65533 65532 65531
65530 65529 65528 65527 65526],
c(8)=[101 102 103 104 105 106 107 108],
d(12)=[1 65535 1 65535 1 65535 1
65535 1 65535 1 65535]
Test(a,10)
Test(b,21)
Test(c,8)
Test(d,12)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Pancake_sort.png Screenshot from Atari 8-bit computer]
<pre>
Array before sort:
[1 4 -1 0 3 7 4 8 20 -6]
Array after sort:
[-6 -1 0 1 3 4 4 7 8 20]
 
Array before sort:
[10 9 8 7 6 5 4 3 2 1 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10]
Array after sort:
[-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10]
 
Array before sort:
[101 102 103 104 105 106 107 108]
Array after sort:
[101 102 103 104 105 106 107 108]
 
Array before sort:
[1 -1 1 -1 1 -1 1 -1 1 -1 1 -1]
Array after sort:
[-1 -1 -1 -1 -1 -1 1 1 1 1 1 1]
</pre>
 
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
procedure Pancake_Sort is
generic
Line 68 ⟶ 454:
end loop;
Ada.Text_IO.New_Line;
end Pancake_Sort;</langsyntaxhighlight>
 
Output:
Line 75 ⟶ 461:
=={{header|ALGOL 68}}==
{{trans|Euphoria}}
<langsyntaxhighlight lang="algol68">PROC flip = ([]INT s, INT n) []INT:
BEGIN
[UPB s]INT ss := s;
Line 116 ⟶ 502:
printf (($"unsorted: "10(g(4) )l$, s));
printf (($"sorted: "10(g(4) )l$, pancake sort(s)))
</syntaxhighlight>
</lang>
{{out}}
<pre>Pancake sort demonstration
Line 122 ⟶ 508:
sorted: -47 -41 -26 -7 -4 -2 +8 +21 +31 +41
</pre>
 
=={{header|AppleScript}}==
Algorithm gleaned from [[Sorting_algorithms/Pancake_sort#Phix|Phix]] and that from [[Sorting_algorithms/Pancake_sort#Euphoria|Euphoria]]
 
<syntaxhighlight lang="applescript">on pancake_sort(aList)
script o
property lst : aList
property len : (count my lst)
on flip(n)
if (n < len) then
set my lst to (reverse of items 1 thru n of my lst) & (items (n + 1) thru len of my lst)
else
set my lst to reverse of my lst
end if
end flip
end script
repeat with i from (count o's lst) to 2 by -1
set maxIdx to 1
set maxVal to beginning of o's lst
repeat with j from 2 to i
tell item j of o's lst
if (it > maxVal) then
set maxIdx to j
set maxVal to it
end if
end tell
end repeat
(* Performancewise, there's little to choose between doing the two 'if' tests below every time and
occasionally flipping unnecessarily. The flips themselves are of of course a daft way to achieve:
set item maxIdx of o's lst to item i of o's lst
set item i of o's lst to maxVal
*)
-- if (maxIdx < i) then
-- if (maxIdx > 1) then ¬
o's flip(maxIdx)
o's flip(i)
-- end if
end repeat
return o's lst
end pancake_sort
 
-- Task code:
local pre, post, astid, output
set pre to {}
repeat 20 times
set end of pre to (random number 100)
end repeat
set post to pancake_sort(pre)
 
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to ", "
set output to "Before: {" & pre & ("}" & linefeed & "After: {" & post & "}")
set AppleScript's text item delimiters to astid
return output</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">"Before: {23, 72, 40, 43, 91, 38, 23, 58, 26, 59, 12, 18, 27, 39, 69, 74, 11, 41, 3, 40}
After: {3, 11, 12, 18, 23, 23, 26, 27, 38, 39, 40, 40, 41, 43, 58, 59, 69, 72, 74, 91}"</syntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program pancakeSort.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
 
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessSortOk: .asciz "Table sorted.\n"
szMessSortNok: .asciz "Table not sorted !!!!!.\n"
sMessResult: .asciz "Value : @ \n"
sMessCounter: .asciz "sorted in @ flips \n"
szCarriageReturn: .asciz "\n"
.align 4
#TableNumber: .int 1,11,3,6,2,5,9,10,8,4,7
TableNumber: .int 10,9,8,7,6,5,4,3,2,1
.equ NBELEMENTS, (. - TableNumber) / 4
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrTableNumber @ address number table
mov r1,#0 @ first element
mov r2,#NBELEMENTS @ number of élements
mov r10,#0 @ flips counter
bl pancakeSort
ldr r0,iAdrTableNumber @ address number table
bl displayTable
mov r0,r10 @ display counter
ldr r1,iAdrsZoneConv @
bl conversion10S @ décimal conversion
ldr r0,iAdrsMessCounter
ldr r1,iAdrsZoneConv @ insert conversion
bl strInsertAtCharInc
bl affichageMess @ display message
ldr r0,iAdrTableNumber @ address number table
mov r1,#NBELEMENTS @ number of élements
bl isSorted @ control sort
cmp r0,#1 @ sorted ?
beq 1f
ldr r0,iAdrszMessSortNok @ no !! error sort
bl affichageMess
b 100f
1: @ yes
ldr r0,iAdrszMessSortOk
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsMessResult: .int sMessResult
iAdrTableNumber: .int TableNumber
iAdrszMessSortOk: .int szMessSortOk
iAdrszMessSortNok: .int szMessSortNok
iAdrsMessCounter: .int sMessCounter
/******************************************************************/
/* control sorted table */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the number of elements > 0 */
/* r0 return 0 if not sorted 1 if sorted */
isSorted:
push {r2-r4,lr} @ save registers
mov r2,#0
ldr r4,[r0,r2,lsl #2]
1:
add r2,#1
cmp r2,r1
movge r0,#1
bge 100f
ldr r3,[r0,r2, lsl #2]
cmp r3,r4
movlt r0,#0
blt 100f
mov r4,r3
b 1b
100:
pop {r2-r4,lr}
bx lr @ return
/******************************************************************/
/* flip */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains first start index
/* r2 contains the number of elements */
/* r3 contains the position of flip */
flip:
push {r1-r6,lr} @ save registers
add r10,r10,#1 @ flips counter
cmp r3,r2
subge r3,r2,#1 @ last index if position >= size
mov r4,r1
1:
cmp r1,r3
bge 100f
ldr r5,[r0,r1,lsl #2] @ load value first index
ldr r6,[r0,r3,lsl #2] @ load value position index
str r6,[r0,r1,lsl #2] @ inversion
str r5,[r0,r3,lsl #2] @
sub r3,r3,#1
add r1,r1,#1
b 1b
100:
pop {r1-r6,lr}
bx lr @ return
/******************************************************************/
/* pancake sort */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains first start index
/* r2 contains the number of elements */
pancakeSort:
push {r1-r9,lr} @ save registers
sub r7,r2,#1
1:
mov r5,r1 @ index
mov r4,#0 @ max
mov r3,#0 @ position
mov r8,#0 @ top sorted
ldr r9,[r0,r5,lsl #2] @ load value A[i-1]
2:
ldr r6,[r0,r5,lsl #2] @ load value
cmp r6,r4 @ compare max
movge r4,r6
movge r3,r5
cmp r6,r9 @ cmp A[i] A[i-1] sorted ?
movlt r8,#1 @ no
mov r9,r6 @ A[i-1] = A[i]
add r5,r5,#1 @ increment index
cmp r5,r7 @ end
ble 2b
cmp r8,#0 @ sorted ?
beq 100f @ yes -> end
cmp r3,r7 @ position ok ?
beq 3f @ yes
cmp r3,#0 @ first position ?
blne flip @ flip if not greather in first position
mov r3,r7 @ and flip the whole stack
bl flip @
3:
subs r7,r7,#1 @ decrement number of pancake
bge 1b @ and loop
100:
pop {r1-r9,lr}
bx lr @ return
 
/******************************************************************/
/* Display table elements */
/******************************************************************/
/* r0 contains the address of table */
displayTable:
push {r0-r3,lr} @ save registers
mov r2,r0 @ table address
mov r3,#0
1: @ loop display table
ldr r0,[r2,r3,lsl #2]
ldr r1,iAdrsZoneConv @
bl conversion10S @ décimal conversion
ldr r0,iAdrsMessResult
ldr r1,iAdrsZoneConv @ insert conversion
bl strInsertAtCharInc
bl affichageMess @ display message
add r3,#1
cmp r3,#NBELEMENTS - 1
ble 1b
ldr r0,iAdrszCarriageReturn
bl affichageMess
mov r0,r2
100:
pop {r0-r3,lr}
bx lr
iAdrsZoneConv: .int sZoneConv
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
 
</syntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">pancakeSort: function [items][
arr: new items
len: size arr
loop (len-1)..1 'endIdx [
maxim: max slice arr 0 endIdx
maximIdx: index arr maxim
if maximIdx=endIdx -> continue
 
if maximIdx > 0 [
arr: (reverse slice arr 0 maximIdx) ++ slice arr maximIdx+1 (size arr)-1
]
 
arr: (reverse slice arr 0 endIdx) ++ slice arr endIdx+1 (size arr)-1
]
arr
]
 
print pancakeSort [3 1 2 8 5 7 9 4 6]</syntaxhighlight>
 
{{out}}
 
<pre>1 2 3 4 5 6 7 8 9</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">;---------------------------------------------------------------------------
Loop { ; test loop
;---------------------------------------------------------------------------
Line 172 ⟶ 850:
Return, List
}
</syntaxhighlight>
</lang>
 
=={{header|BASIC}}==
Line 178 ⟶ 856:
{{works with|QBasic}}
 
<langsyntaxhighlight lang="qbasic">RANDOMIZE TIMER
 
DIM nums(9) AS INTEGER
Line 223 ⟶ 901:
PRINT
END IF
NEXT</langsyntaxhighlight>
 
Sample output:
Line 244 ⟶ 922:
This is a graphical variation of the above.
 
<langsyntaxhighlight lang="qbasic">RANDOMIZE TIMER
 
CONST delay = .1 'controls display speed
Line 298 ⟶ 976:
ttmp = TIMER
DO WHILE TIMER < ttmp + delay: LOOP
RETURN</langsyntaxhighlight>
 
Sample output:
Line 304 ⟶ 982:
[[File:Pancake.gif]]
 
=={{header|Batch File}}==
{{trans|BASIC}}
<syntaxhighlight lang="dos">:: Pancake Sort from Rosetta Code
:: Batch File Implementation
@echo off
setlocal enabledelayedexpansion
 
:: put the input sequence of integers (only) on the list variable.
set "list=-2 0 -1 5 2 7 4 3 6 -1 7 2 1 8"
 
:: create a pseudo-array; start at 0.
set "range=-1"
for %%l in (%list%) do (
set /a "range+=1"
set "num!range!=%%l"
)
 
:: scramble (remove this if you do not want to scramble the integers)
for /l %%l in (%range%,-1,1) do (
set /a "n=%random% %% %%l"
rem swapping...
for %%? in (num!n!) do set "swaptemp=!%%?!"
set "num!n!=!num%%l!"
set "num%%l=!swaptemp!"
)
 
:: display initial condition
set "output="
for /l %%l in (0,1,%range%) do set "output=!output! !num%%l!"
echo(Initial Sequence:
echo(
echo( ^>^> %output%
echo(
echo(Sorting:
echo(
 
:: begin sort
for /l %%l in (%range%,-1,1) do (
set "n=0"
for /l %%m in (1,1,%%l) do (
for %%? in (num!n!) do if !%%?! lss !num%%m! set "n=%%m"
)
 
if !n! lss %%l (
if !n! gtr 0 (
set /a "tempvar1=!n!/2" %== corresponds to (n \ 2) from BASIC code ==%
for /l %%m in (0,1,!tempvar1!) do (
set /a "tempvar2=!n!-%%m" %== corresponds to (n - L0) from BASIC code ==%
rem swapping...
for %%? in (num!tempvar2!) do set "swaptemp=!%%?!"
set "num!tempvar2!=!num%%m!"
set "num%%m=!swaptemp!"
)
rem display the action
set "output="
for /l %%x in (0,1,%range%) do set "output=!output! !num%%x!"
echo( ^>^> !output!
)
 
set /a "tempvar1=%%l/2" %== corresponds to (L1 \ 2) from BASIC code ==%
for /l %%m in (0,1,!tempvar1!) do (
set /a "tempvar2=%%l-%%m" %== corresponds to (L1 - L0) from BASIC code ==%
rem swapping...
for %%? in (num!tempvar2!) do set "swaptemp=!%%?!"
set "num!tempvar2!=!num%%m!"
set "num%%m=!swaptemp!"
)
rem display the action
set output=
for /l %%x in (0,1,%range%) do set "output=!output! !num%%x!"
echo. ^>^> !output!
)
)
)
 
echo DONE^^!
exit /b 0</syntaxhighlight>
{{Out}}
<pre>Initial Sequence:
 
>> 8 3 5 6 -1 0 -2 2 -1 7 2 1 4 7
 
Sorting:
 
>> 7 4 1 2 7 -1 2 -2 0 -1 6 5 3 8
>> 3 5 6 -1 0 -2 2 -1 7 2 1 4 7 8
>> 7 -1 2 -2 0 -1 6 5 3 2 1 4 7 8
>> 4 1 2 3 5 6 -1 0 -2 2 -1 7 7 8
>> 6 5 3 2 1 4 -1 0 -2 2 -1 7 7 8
>> -1 2 -2 0 -1 4 1 2 3 5 6 7 7 8
>> 4 -1 0 -2 2 -1 1 2 3 5 6 7 7 8
>> 3 2 1 -1 2 -2 0 -1 4 5 6 7 7 8
>> -1 0 -2 2 -1 1 2 3 4 5 6 7 7 8
>> 2 -2 0 -1 -1 1 2 3 4 5 6 7 7 8
>> 2 1 -1 -1 0 -2 2 3 4 5 6 7 7 8
>> -2 0 -1 -1 1 2 2 3 4 5 6 7 7 8
>> 0 -2 -1 -1 1 2 2 3 4 5 6 7 7 8
>> -1 -1 -2 0 1 2 2 3 4 5 6 7 7 8
>> -2 -1 -1 0 1 2 2 3 4 5 6 7 7 8
DONE!</pre>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> DIM test(9)
test() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1
PROCpancakesort(test())
Line 338 ⟶ 1,117:
SWAP a(i%), a(n%-i%)
NEXT
ENDPROC</langsyntaxhighlight>
'''Output:'''
<pre>
Line 346 ⟶ 1,125:
=={{header|C}}==
'''The function that sorts:'''
<langsyntaxhighlight lang="c">int pancake_sort(int *list, unsigned int length)
{
//If it's less than 2 long, just return it as sorting isn't really needed...
Line 387 ⟶ 1,166:
 
return moves;
}</langsyntaxhighlight>
 
Where do_flip() is a simple function to flip a part of an array:
<langsyntaxhighlight lang="c">void do_flip(int *list, int length, int num)
{
int swap;
Line 400 ⟶ 1,179:
list[num]=swap;
}
}</langsyntaxhighlight>
 
'''Testing the function:'''
<langsyntaxhighlight lang="c">int main(int argc, char **argv)
{
//Just need some random numbers. I chose <100
Line 422 ⟶ 1,201:
print_array(list, 9);
printf(" - with a total of %d moves\n", moves);
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="c sharp|c#">
public static class PancakeSorter
{
public static void Sort<T>(List<T> list) where T : IComparable
{
if (list.Count < 2)
{
return;
}
int i, a, max_num_pos;
for (i = list.Count; i > 1; i--)
{
max_num_pos = 0;
for (a = 0; a < i; a++)
{
if (list[a].CompareTo(list[max_num_pos]) > 0)
{
max_num_pos = a;
}
}
if (max_num_pos == i - 1)
{
continue;
}
if (max_num_pos > 0)
{
Flip(list, list.Count, max_num_pos + 1);
}
Flip(list, list.Count, i);
}
return;
}
private static void Flip<T>(List<T> list, int length, int num)
{
for (int i = 0; i < --num; i++)
{
T swap = list[i];
list[i] = list[num];
list[num] = swap;
}
}
}
</syntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="c">#include <algorithm>
#include <iostream>
#include <iterator>
Line 474 ⟶ 1,298:
std::copy(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}</langsyntaxhighlight>Output:<pre>4 10 11 15 14 16 17 1 6 9 3 7 19 2 0 12 5 18 13 8
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 </pre>
 
=={{header|C sharp|C#}}==
<lang C sharp|C#>
public static class PancakeSorter
{
public static void Sort<T>(List<T> list) where T : IComparable
{
if (list.Count < 2)
{
return;
}
int i, a, max_num_pos;
for (i = list.Count; i > 1; i--)
{
max_num_pos = 0;
for (a = 0; a < i; a++)
{
if (list[a].CompareTo(list[max_num_pos]) > 0)
{
max_num_pos = a;
}
}
if (max_num_pos == i - 1)
{
continue;
}
if (max_num_pos > 0)
{
Flip(list, list.Count, max_num_pos + 1);
}
Flip(list, list.Count, i);
}
return;
}
private static void Flip<T>(List<T> list, int length, int num)
{
for (int i = 0; i < --num; i++)
{
T swap = list[i];
list[i] = list[num];
list[num] = swap;
}
}
}
</lang>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">
(defn pancake-sort
[arr]
Line 534 ⟶ 1,313:
head (reverse torev)]
(cons mx (pancake-sort (concat (drop 1 head) (drop 1 tail))))))))
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun pancake-sort (seq)
"A destructive version of Pancake Sort that works with either lists or arrays of numbers."
(defun flip (lst index)
Line 547 ⟶ 1,326:
(flip lst (1+ index)))
(flip lst i)
finally (return (coerce lst (type-of seq)))))</langsyntaxhighlight>
Output:
<langsyntaxhighlight lang="lisp">CL-USER> (pancake-sort '(6 7 8 9 2 5 3 4 1)) ;list
(1 2 3 4 5 6 7 8 9)
CL-USER> (pancake-sort #(6 7 8 9 2 5 3 4 1)) ;array
#(1 2 3 4 5 6 7 8 9)
CL-USER> (pancake-sort #(6.5 7.5 8 9 2 5 3 4 1.0)) ;array with integer and floating point values
#(1.0 2 3 4 5 6.5 7.5 8 9)</langsyntaxhighlight>
 
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm;
 
void pancakeSort(bool tutor=false, T)(T[] data) {
Line 581 ⟶ 1,360:
data.pancakeSort!true;
data.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>With: 769248135 doflip 3
Line 598 ⟶ 1,377:
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
PANCAKE_SORT [G -> COMPARABLE]
Line 704 ⟶ 1,483:
 
end
</syntaxhighlight>
</lang>
 
Test:
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 740 ⟶ 1,519:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 746 ⟶ 1,525:
Sorted: -7 1 1 3 5 27 32 99
</pre>
 
=={{header|Elena}}==
ELENA 45.10 :
{{trans|C#}}
<langsyntaxhighlight lang="elena">import extensions;
extension op
Line 811 ⟶ 1,591:
public program()
{
var list := new int[]::({6, 7, 8, 9, 2, 5, 3, 4, 1)};
console.printLine("before:", list.asEnumerable());
console.printLine("after :", list.pancakeSort().asEnumerable())
}</langsyntaxhighlight>
{{out}}
<pre>
Line 823 ⟶ 1,603:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Sort do
def pancake_sort(list) when is_list(list), do: pancake_sort(list, length(list))
Line 849 ⟶ 1,629:
 
IO.inspect list = Enum.shuffle(1..9)
IO.inspect Sort.pancake_sort(list)</langsyntaxhighlight>
 
{{out}}
Line 858 ⟶ 1,638:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function flip(sequence s, integer n)
object temp
for i = 1 to n/2 do
Line 891 ⟶ 1,671:
 
? s
? pancake_sort(s)</langsyntaxhighlight>
 
Output:
Line 899 ⟶ 1,679:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">open System
 
let show data = data |> Array.iter (printf "%d ") ; printfn ""
Line 917 ⟶ 1,697:
loop partialSort (limit-1)
 
loop items ((Array.length items)-1)</langsyntaxhighlight>
Usage: pancakeSort [|31; 41; 59; 26; 53; 58; 97; 93; 23; 84|] |> show
 
Line 927 ⟶ 1,707:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">program Pancake_Demo
implicit none
Line 963 ⟶ 1,743:
end subroutine
end program Pancake_Demo</langsyntaxhighlight>
Output:
<pre>
Line 980 ⟶ 1,760:
1 2 3 4 5 6 7 8
</pre>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 11-04-2017
' compile with: fbc -s console
' for boundry checks on array's compile with: fbc -s console -exx
Line 1,084 ⟶ 1,865:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>unsorted -1 -4 1 6 7 5 2 -3 4 -5 -2 -6 0 3 -7
Line 1,105 ⟶ 1,886:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,138 ⟶ 1,919:
a[l], a[r] = a[r], a[l]
}
}</langsyntaxhighlight>
Output:
<pre>
Line 1,147 ⟶ 1,928:
=={{header|Groovy}}==
This formulation of the pancake sort achieves stability by picking the last index (rather than, say, the first) in the remaining sublist that matches the max value of the remaining sublist. Performance is enhanced somewhat by not flipping if the ''flipPoint'' is already at the end of the remaining sublist.
<langsyntaxhighlight lang="groovy">def makeSwap = { a, i, j = i+1 -> print "."; a[[j,i]] = a[[i,j]] }
 
def flip = { list, n -> (0..<((n+1)/2)).each { makeSwap(list, it, n-it) } }
Line 1,162 ⟶ 1,943:
}
list
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">println (pancakeSort([23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4]))
println (pancakeSort([88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1]))
println ()
Line 1,173 ⟶ 1,954:
println (pancakeSort([10.0, 10.00, 10, 1]))
println (pancakeSort([10.00, 10, 10.0, 1]))
println (pancakeSort([10.00, 10.0, 10, 1]))</langsyntaxhighlight>
The use of decimals and integers that compare as equal demonstrates, but of course not '''prove''', that the sort is stable.
 
Line 1,188 ⟶ 1,969:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List
import Control.Arrow
import Control.Monad
Line 1,201 ⟶ 1,982:
dopcs ([],rs) = rs
dopcs ([x],rs) = x:rs
dopcs (xs,rs) = dopcs $ (init &&& (:rs).last ) $ dblflipIt xs</langsyntaxhighlight>
Example:
<langsyntaxhighlight lang="haskell">*Main> dopancakeSort [3,2,1,0,2]
[0,1,2,2,3]</langsyntaxhighlight>
 
=={{header|Haxe}}==
<syntaxhighlight lang="haxe">class PancakeSort {
@:generic
inline private static function flip<T>(arr:Array<T>, num:Int) {
var i = 0;
while (i < --num) {
var temp = arr[i];
arr[i++] = arr[num];
arr[num] = temp;
}
}
 
@:generic
public static function sort<T>(arr:Array<T>) {
if (arr.length < 2) return;
 
var i = arr.length;
while (i > 1) {
var maxNumPos = 0;
for (a in 0...i) {
if (Reflect.compare(arr[a], arr[maxNumPos]) > 0)
maxNumPos = a;
}
if (maxNumPos == i - 1) i--;
if (maxNumPos > 0) flip(arr, maxNumPos + 1);
flip(arr, i--);
}
}
}
 
class Main {
static function main() {
var integerArray = [1, 10, 2, 5, -1, 5, -19, 4, 23, 0];
var floatArray = [1.0, -3.2, 5.2, 10.8, -5.7, 7.3,
3.5, 0.0, -4.1, -9.5];
var stringArray = ['We', 'hold', 'these', 'truths', 'to',
'be', 'self-evident', 'that', 'all',
'men', 'are', 'created', 'equal'];
Sys.println('Unsorted Integers: ' + integerArray);
PancakeSort.sort(integerArray);
Sys.println('Sorted Integers: ' + integerArray);
Sys.println('Unsorted Floats: ' + floatArray);
PancakeSort.sort(floatArray);
Sys.println('Sorted Floats: ' + floatArray);
Sys.println('Unsorted Strings: ' + stringArray);
PancakeSort.sort(stringArray);
Sys.println('Sorted Strings: ' + stringArray);
}
}</syntaxhighlight>
 
{{out}}
<pre>
Unsorted Integers: [1,10,2,5,-1,5,-19,4,23,0]
Sorted Integers: [-19,-1,0,1,2,4,5,5,10,23]
Unsorted Floats: [1,-3.2,5.2,10.8,-5.7,7.3,3.5,0,-4.1,-9.5]
Sorted Floats: [-9.5,-5.7,-4.1,-3.2,0,1,3.5,5.2,7.3,10.8]
Unsorted Strings: [We,hold,these,truths,to,be,self-evident,that,all,men,are,created,equal]
Sorted Strings: [We,all,are,be,created,equal,men,self-evident,hold,that,these,to,truths]
</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main() #: demonstrate various ways to sort a list and string
demosort(pancakesort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty")
pancakeflip := pancakeflipshow # replace pancakeflip procedure with a variant that displays each flip
Line 1,247 ⟶ 2,088:
every writes(" ["|right(!X,4)|" ]\n") # show X
return X
end</langsyntaxhighlight>
 
Note: This example relies on [[Sorting_algorithms/Bubble_sort#Icon| the supporting procedures 'sortop', and 'demosort' in Bubble Sort]]. The full demosort exercises the named sort of a list with op = "numeric", "string", ">>" (lexically gt, descending),">" (numerically gt, descending), a custom comparator, and also a string.
Line 1,276 ⟶ 2,117:
=={{header|J}}==
{{eff note|J|/:~}}
<langsyntaxhighlight Jlang="j">flip=: C.~ C.@i.@-
unsorted=: #~ 1 , [: >./\. 2 >/\ ]
FlDown=: flip 1 + (i. >./)@unsorted
FlipUp=: flip 1 >. [:+/>./\&|.@(< {.)
 
pancake=: FlipUp@FlDown^:_</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight Jlang="j"> (,:pancake) ?~9
1 0 8 7 4 6 3 5 2
0 1 2 3 4 5 6 7 8</langsyntaxhighlight>
 
See the [[Talk:Sorting_algorithms/Pancake_sort#J_implementation|discussion page]] for illustrations of the other words.
Line 1,293 ⟶ 2,134:
=={{header|Java}}==
 
<langsyntaxhighlight lang="java">
public class PancakeSort
{
Line 1,375 ⟶ 2,216:
System.out.println(pancakes);
}
}</langsyntaxhighlight>
 
Example:
<langsyntaxhighlight lang="bash">$ java PancakeSort 1 2 5 4 3 10 9 8 7
flip(0..5): 10 3 4 5 2 1 9 8 7
flip(0..8): 7 8 9 1 2 5 4 3 10
Line 1,393 ⟶ 2,234:
flip(0..4): 7 6 5 4 3 2 1 8 9
flip(0..6): 1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 </langsyntaxhighlight>
 
===Using Java 8===
<syntaxhighlight lang="java">
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.IntStream;
 
public final class PancakeSort {
 
public static void main(String[] aArgs) {
List<Integer> numbers = Arrays.asList( 1, 5, 4, 2, 3, 2, 8, 6, 7 );
System.out.println("Initial list: " + numbers);
pancakeSort(numbers);
}
private static void pancakeSort(List<Integer> aList) {
for ( int i = aList.size() - 1; i >= 0; i-- ) {
int index = IntStream.rangeClosed(0, i).boxed().max(Comparator.comparing(aList::get)).get();
if ( index != i ) {
flip(aList, index);
flip(aList, i);
}
}
}
private static void flip(List<Integer> aList, int aIndex) {
if ( aIndex > 0 ) {
Collections.reverse(aList.subList(0, aIndex + 1));
System.out.println("flip 0.." + aIndex + " --> " + aList);
}
}
 
}
</syntaxhighlight>
{{ out }}
<pre>
Initial list: [1, 5, 4, 2, 3, 2, 8, 6, 7]
flip 0..6 --> [8, 2, 3, 2, 4, 5, 1, 6, 7]
flip 0..8 --> [7, 6, 1, 5, 4, 2, 3, 2, 8]
flip 0..7 --> [2, 3, 2, 4, 5, 1, 6, 7, 8]
flip 0..4 --> [5, 4, 2, 3, 2, 1, 6, 7, 8]
flip 0..5 --> [1, 2, 3, 2, 4, 5, 6, 7, 8]
flip 0..2 --> [3, 2, 1, 2, 4, 5, 6, 7, 8]
flip 0..3 --> [2, 1, 2, 3, 4, 5, 6, 7, 8]
flip 0..2 --> [2, 1, 2, 3, 4, 5, 6, 7, 8]
flip 0..1 --> [1, 2, 2, 3, 4, 5, 6, 7, 8]
</pre>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">Array.prototype.pancake_sort = function () {
for (var i = this.length - 1; i >= 1; i--) {
// find the index of the largest element not yet sorted
Line 1,428 ⟶ 2,319:
}
ary = [7,6,5,9,8,4,3,1,2,0]
sorted = ary.concat().pancake_sort();</langsyntaxhighlight>
 
=={{header|jq}}==
{{works with|jq|1.4}}
This version skips the pair of flips if the focal item is already in place.
<langsyntaxhighlight lang="jq">def pancakeSort:
 
def flip(i):
Line 1,454 ⟶ 2,345:
| if ($i == $max) then .
else flip($max) | flip($i)
end ) ;</langsyntaxhighlight>
'''Example''':
<langsyntaxhighlight lang="jq">[range(0;2), null, 1.0, 0.5, [1], [2], {"b":1}, {"a":2}, range(2;4)]
| pancakeSort</langsyntaxhighlight>
 
{{out}}
<langsyntaxhighlight lang="sh">$ jq -M -c -n -f pancake_sort.jq
[null,0,0.5,1,1,2,3,[1],[2],{"a":2},{"b":1}]</langsyntaxhighlight>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">function pancakesort!(arr::Vector{<:Real})
{{works with|Julia|0.6}}
 
<lang julia>function pancakesort!(arr::Vector{<:Real})
len = length(arr)
if len < 2 return arr end
for i in len:-1:2
j = indmaxfindmax(arr[1:i])[2]
if i == j continue end
arr[1:j] = reverse(arr[1:j])
Line 1,479 ⟶ 2,368:
 
v = rand(-10:10, 10)
println("# unordered: $v\n -> ordered: ", pancakesort!(v))</langsyntaxhighlight>
 
{{out}}
Line 1,486 ⟶ 2,375:
 
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">fun pancakeSort(a: IntArray) {
<lang scala>// version 1.1.2
/** Returns the index of the highest number in the range 0 until n. */
fun indexOfMax(n: Int): Int = (0 until n).maxByOrNull{ a[it] }!!
/** Flips the elements in the range 0 .. n. */
fun flip(index: Int) {
a.reverse(0, index + 1)
}
 
for (n in a.size downTo 2) { // successively reduce size of array by 1
class PancakeSort(private val a: IntArray) {
val index = indexOfMax(n) // find index of largest
init {
forif (nindex in!= a.sizen downTo- 21) { // successivelyif reduceit's sizenot ofalready arrayat bythe 1end
valif (index => indexOfMax(n0) { // findif indexit's not already at ofthe largestbeginning
if (index != n - 1flip(index) { // if it's not alreadymove atlargest theto endbeginning
println("${a.contentToString()} after flipping first ${index + 1}")
if (index > 0) { // if it's not already at the beginning
flip(index) // move largest to beginning
println("${a.contentToString()} after flipping first ${index + 1}")
}
flip(n - 1) // move largest to end
println("${a.contentToString()} after flipping first $n")
}
flip(n - 1) // move largest to end
}
println("${a.contentToString()} after flipping first $n")
}
 
private fun indexOfMax(n: Int): Int {
var index = 0
for (i in 1 until n) {
if (a[i] > a[index]) index = i
}
return index
}
 
private fun flip(index: Int) {
var i = index
var j = 0
while (j < i) {
val temp = a[j]
a[j] = a[i]
a[i] = temp
j++
i--
}
}
}
 
fun main(args: Array<String>) {
val a = intArrayOf(7, 6, 9, 2, 4, 8, 1, 3, 5)
println("${a.contentToString()} initially")
PancakeSortpancakeSort(a)
}</langsyntaxhighlight>
 
{{out}}
Line 1,548 ⟶ 2,421:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">-- Initialisation
math.randomseed(os.time())
numList = {step = 0, sorted = 0}
Line 1,613 ⟶ 2,486:
numList:show()
until numList:isSorted()
</syntaxhighlight>
</lang>
{{out}}
<pre>Initial state: -67 61 80 47 21 74 43 22 66 -66
Line 1,634 ⟶ 2,507:
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">flip := proc(arr, i)
local start, temp, icopy;
temp, start, icopy := 0,1,i:
Line 1,663 ⟶ 2,536:
end do:
print(arr);
end proc:</langsyntaxhighlight>
{{Out|Example}}
Input: arr := Array([17,3,72,0,36,2,3,8,40,1]):
Line 1,677 ⟶ 2,550:
[0, 1, 2, 3, 3, 8, 17, 36, 40, 72]</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">ClearAll[LMaxPosition, Flip, pancakeSort]
<lang Mathematica>LMaxPosition[ a_, n_ ] := Part[Position[a[[;;n]],Max[a[[;;n]]]],1,1]
LMaxPosition[a_, n_] := With[{b = Take[a, n]}, First[Ordering[b, -1]]]
 
SetAttributes[Flip,HoldFirst HoldAll]; Flip[a_] := Set[a,Reverse[a]]
Flip[a_] := Set[a, Reverse[a]]
 
pancakeSort[a_in_] : = ForModule[{n, lm, a = Length[a]in, nflips >= 1, n--0},
Do[
If[LMaxPosition[a,n] < n,
Flip[a[[;; lm = LMaxPosition[a, n]]]]; Print[a];
If[lm < n,
Flip[a[[;;n]]]; Print[a];
Flip[a[[;; lm]]];
];
Flip[a[[;; n]]];
];</lang>
];
 
,
<pre>(* each major sort step is printed in example usage *)
pancakeSort[{6, 7, 8 {n, 9Length[a], 2, 5, 3, 4, -1}]
];
 
a
{9,8,7,6,2,5,3,4,1}
]
pancakeSort[{6, 7, 8, 9, 2, 5, 3, 4, 1}]</syntaxhighlight>
{{out}}
<pre>{9,8,7,6,2,5,3,4,1}
{1,4,3,5,2,6,7,8,9}
{5,3,4,1,2,6,7,8,9}
Line 1,702 ⟶ 2,579:
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight MATLABlang="matlab">function list = pancakeSort(list)
 
for i = (numel(list):-1:2)
Line 1,729 ⟶ 2,606:
end
end %for
end %pancakeSort</langsyntaxhighlight>
 
Sample Usage:
<langsyntaxhighlight MATLABlang="matlab">>> pancakeSort([4 3 1 5 6 2])
 
ans =
 
6 5 4 3 2 1</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<langsyntaxhighlight MAXScriptlang="maxscript">fn flipArr arr index =
(
local new = #()
Line 1,767 ⟶ 2,644:
return arr
)
)</langsyntaxhighlight>
Output:
<syntaxhighlight lang="maxscript">
<lang MAXScript>
a = for i in 1 to 15 collect random 0 20
#(8, 13, 2, 0, 10, 8, 1, 15, 4, 7, 6, 9, 11, 3, 5)
pancakeSort a
#(0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10, 11, 13, 15)
</syntaxhighlight>
</lang>
 
=={{header|NetRexx}}==
Sorts integers, decimal numbers and strings because they're all the same to NetRexx.
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,859 ⟶ 2,736:
 
return clist
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,882 ⟶ 2,759:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import algorithm
 
proc pancakeSort[T](list: var openarray[T]) =
Line 1,892 ⟶ 2,769:
for i in countdown(length, 2):
var maxNumPos = 0
for a in 0 .. < i:
if list[a] > list[maxNumPos]:
maxNumPos = a
Line 1,907 ⟶ 2,784:
var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]
pancakeSort a
echo a</langsyntaxhighlight>
Output:
<pre>@[-31, 0, 2, 2, 4, 65, 83, 99, 782]</pre>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let rec sorted = function
| [] -> (true)
| x::y::_ when x > y -> (false)
Line 1,954 ⟶ 2,831:
print_list res;
Printf.printf " sorted in %d loops\n" n;
;;</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">pancakeSort(v)={
my(top=#v);
while(top>1,
Line 1,976 ⟶ 2,853:
);
v
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">Program PancakeSort (output);
 
procedure flip(var b: array of integer; last: integer);
Line 2,043 ⟶ 2,920:
end;
writeln;
end.</langsyntaxhighlight>
Output:
<pre>:>./PancakeSort
Line 2,053 ⟶ 2,930:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub pancake {
my @x = @_;
for my $idx (0 .. $#x - 1) {
Line 2,071 ⟶ 2,948:
@a = pancake(@a);
print "After @a\n";
</syntaxhighlight>
</lang>
Sample output:
<pre>Before 57 37 35 35 22 58 70 53 77 15
After 15 22 35 35 37 53 57 58 70 77</pre>
 
=={{header|Perl 6}}==
<lang perl6>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 @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;
}
my @data = 6, 7, 2, 1, 8, 9, 5, 3, 4;
say 'input = ' ~ @data;
say 'output = ' ~ @data.&pancake_sort;
</lang>
 
Output:<pre>input = 6 7 2 1 8 9 5 3 4
output = 1 2 3 4 5 6 7 8 9
</pre>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
Copy of [[Sorting_algorithms/Pancake_sort#Euphoria|Euphoria]]
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<lang Phix>function flip(sequence s, integer n)
for i=1 to floor(n/2) do
{s[i],s[n-i+1]} = {s[n-i+1],s[i]}
end for
return s
end function
<span style="color: #008080;">function</span> <span style="color: #000000;">pancake_sort</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
function pancake_sort(sequence s)
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
integer m
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">to</span> <span style="color: #000000;">2</span> <span style="color: #008080;">by</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
for i=length(s) to 2 by -1 do
<span style="color: #004080;">integer</span> <span style="color: #000000;">m</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">largest</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #004600;">true</span><span style="color: #0000FF;">)</span>
m = 1
<span style="color: #008080;">if</span> <span style="color: #000000;">m</span><span style="color: #0000FF;"><</span><span style="color: #000000;">i</span> <span style="color: #008080;">then</span>
for j=2 to i do
<span style="color: #008080;">if</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">></span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
if s[j]>s[m] then
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">m</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">reverse</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">m</span><span style="color: #0000FF;">])</span>
m = j
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">reverse</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if m<i then
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
if m>1 then
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
s = flip(s,m)
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
end if
s = flip(s,i)
end if
end for
return s
end function
<span style="color: #008080;">constant</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">shuffle</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">))</span>
constant s = shuffle(tagset(10))
<span style="color: #0000FF;">?</span> <span style="color: #000000;">s</span>
? s
<span style="color: #0000FF;">?</span> <span style="color: #000000;">pancake_sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
? pancake_sort(s) </lang>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,139 ⟶ 2,980:
{1,2,3,4,5,6,7,8,9,10}
</pre>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">go =>
Nums = [6,7,8,9,2,5,3,4,1],
println(Nums),
Sorted = pancake_sort(Nums),
println(Sorted),
nl.
 
pancake_sort(L) = L =>
T = L.len,
while (T > 1)
Ix = argmax(L[1..T]),
if Ix == 1 then
L := L[1..T].reverse ++ L.slice(T+1),
T := T-1
else
L := L[1..Ix].reverse ++ L.slice(Ix+1)
end
end.
 
% Get the index of the (first) maximal value in L
argmax(L) = MaxIx =>
Max = max(L),
MaxIx = [I : I in 1..L.length, L[I] == Max].first.</syntaxhighlight>
 
{{out}}
<pre>[6,7,8,9,2,5,3,4,1]
[1,2,3,4,5,6,7,8,9]</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de pancake (Lst)
(prog1 (flip Lst (index (apply max Lst) Lst))
(for (L @ (cdr (setq Lst (cdr L))) (cdr L))
(con L (flip Lst (index (apply max Lst) Lst))) ) ) )</langsyntaxhighlight>
Output:
<pre>: (trace 'flip)
Line 2,169 ⟶ 3,039:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
pancake_sort: procedure options (main); /* 23 April 2009 */
declare a(10) fixed, (i, n, loc) fixed binary;
Line 2,205 ⟶ 3,075:
 
end pancake_sort;
</syntaxhighlight>
</lang>
Output:
<syntaxhighlight lang="text">
3 9 2 7 10 1 8 5 4 6
6 4 5 8 1 3 9 2 7 10
Line 2,218 ⟶ 3,088:
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
<langsyntaxhighlight PowerShelllang="powershell">Function FlipPancake( [Object[]] $indata, $index = 1 )
{
$data=$indata.Clone()
Line 2,258 ⟶ 3,128:
}
 
$l = 100; PancakeSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( 0, $l - 1 ) } )</langsyntaxhighlight>
 
=={{header|PureBasic}}==
 
<langsyntaxhighlight PureBasiclang="purebasic">If OpenConsole()
Define i, j, k, Loops
Dim Pile(9)
Line 2,304 ⟶ 3,174:
Print(#CRLF$+#CRLF$+"Press ENTER to quit."): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
 
'''Output can look like
Line 2,315 ⟶ 3,185:
=={{header|Python}}==
'''The function:'''
<langsyntaxhighlight lang="python">tutor = False
 
def pancakesort(data):
Line 2,334 ⟶ 3,204:
% ( ' '.join(str(x) for x in data), size ))
data[:size] = reversed(data[:size])
if tutor: print()</langsyntaxhighlight>
'''A test:'''
<langsyntaxhighlight lang="python">if __name__ == '__main__':
import random
 
Line 2,346 ⟶ 3,216:
print('Original List: %r' % ' '.join(data))
pancakesort(data)
print('Pancake Sorted List: %r' % ' '.join(data))</langsyntaxhighlight>
 
'''Sample output:'''
Line 2,361 ⟶ 3,231:
 
Pancake Sorted List: '1 2 3 4 5 6 7 8 9'</pre>
 
=={{header|Quackery}}==
<syntaxhighlight lang="quackery">[ split reverse join ] is flip ( [ n --> [ )
 
[ 0 swap behead swap
witheach
[ 2dup > iff
[ nip nip
i^ 1+ swap ]
else drop ]
drop ] is smallest ( [ --> n )
 
[ dup size times
[ dup i^ split nip
smallest i^ + flip
i^ flip ] ] is pancakesort ( [ --> [ )</syntaxhighlight>
 
'''Testing in Quackery shell:'''
<pre>/O> [] 23 times [ 10 random join ]
... say "Before: " dup echo cr
... say " After: " pancakesort echo cr
...
Before: [ 1 2 1 5 5 9 7 1 2 3 9 1 9 2 5 0 5 2 6 0 8 3 2 ]
After: [ 0 0 1 1 1 1 2 2 2 2 2 3 3 5 5 5 5 6 7 8 9 9 9 ]
 
Stack empty.</pre>
 
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 2,376 ⟶ 3,273:
(pancake-sort (shuffle (range 0 10)))
;; => '(0 1 2 3 4 5 6 7 8 9)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>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 @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;
}
my @data = 6, 7, 2, 1, 8, 9, 5, 3, 4;
say 'input = ' ~ @data;
say 'output = ' ~ @data.&pancake_sort;
</syntaxhighlight>
 
Output:<pre>input = 6 7 2 1 8 9 5 3 4
output = 1 2 3 4 5 6 7 8 9
</pre>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program sorts and displays an array using the pancake sort algorithm. */
call gen /*generate elements in the @. array.*/
call show 'before sort' /*display the BEFORE array elements.*/
say copies('▒', 60) say copies('▒', 60) /*display a separator line for eyeballs*/
call pancakeSort # /*invoke the pancake sort. Yummy. */
call show ' after sort' /*display the AFTER array elements. */
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
flipinOrder: parse arg yn; do ij=1 for (y+n-1)%2; yyy k=y-i j+1; _=@.i; if @.i=j>@.yyy;k then return @.yyy=_0; end; return 1
panFlip: parse arg y; do i=1 for (y+1)%2; yi=y-i+1; _=@.i; @.i=@.yi; @.yi=_; end; return
show: do k=1 for #; say @element right(k,length(#)) arg(1)':' right(@.k,9); end; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
Line 2,395 ⟶ 3,321:
/* ┌◄─┬──◄─ some paired bread primes which are of the form: (P-3)÷2 and 2∙P+3 */
/* │ │ where P is a prime. Bread primes are related to sandwich & meat primes*/
/* ↓ ↓ ──── ────════ ───── ──────══════ ────── ──────══════ ────── ───────═══════ ─────── ───────═══════ ──────*/
bp=2 17 5 29 7 37 13 61 43 181 47 197 67 277 97 397 113 461 137 557 167 677 173 701,
797 1117 307 1237 1597 463 1861 467
$= bp fibs; #= words($) /*combine the two lists; get # of items*/
do j=1 for #; @.j= word($, j); end /*◄─── obtain a number from the $ list.*/
return /* [↑] populate the @. array with #s*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
pancakeSort: procedure expose @.; parse arg Nn .; if inOrder(n) then return
do Nn=Nn by -1 for Nn-1
!= @.1; ?= 1; do j=2 to Nn; if @.j<=! then iterate
!= @.j; ?= j
end /*j*/
call flippanFlip ?; call flippanFlip Nn
end /*n*/; end return</*N*/syntaxhighlight>
return</lang>
{{out|output|text=&nbsp; when using the internally generated numbers:}}
 
<small>(Shown at three-quarter size.)</small>
<pre style="font-size:75%;height:95ex136ex">
element 1 before sort: 2
element 2 before sort: 17
Line 2,500 ⟶ 3,425:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
pancakeList = [6, 7, 8, 9, 2, 5, 3, 4, 1]
flag = 0
Line 2,530 ⟶ 3,455:
end
return A
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,540 ⟶ 3,465:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">class Array
def pancake_sort!
num_flips = 0
Line 2,561 ⟶ 3,486:
 
p a = (1..9).to_a.shuffle
p a.pancake_sort!</langsyntaxhighlight>
 
'''sample output:'''
Line 2,578 ⟶ 3,503:
 
=={{header|Rust}}==
<langsyntaxhighlight Rustlang="rust">fn pancake_sort<T: Ord>(v: &mut [T]) {
let len = v.len();
// trivial case -- no flips
Line 2,619 ⟶ 3,544:
pancake_sort(&mut strings);
println!("After: {:?}", strings);
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func pancake(a) {
for idx in ^(a.end) {
var min = idx
Line 2,636 ⟶ 3,561:
var arr = 10.of{ 100.irand }
say "Before: #{arr}"
say "After: #{pancake(arr)}"</langsyntaxhighlight>
 
{{out}}
Line 2,646 ⟶ 3,571:
=={{header|Swift}}==
{{trans|Java}}
<langsyntaxhighlight Swiftlang="swift">import Foundation
 
struct PancakeSort {
Line 2,711 ⟶ 3,636:
var a = PancakeSort(arr: arr)
a.sort(arr.count, dir: 1)
println(a.arr)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,725 ⟶ 3,650:
flip(0.. 2): [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
</pre>
 
=={{header|Tailspin}}==
Simplest version, bubblesort style
<syntaxhighlight lang="tailspin">
templates pancakeSort
@: {stack: $, flips: 0"1"};
sink flip
when <2..> do
@pancakeSort.stack(1..$): $@pancakeSort.stack($..1:-1)...;
'$@pancakeSort.stack;$#10;' -> !OUT::write
@pancakeSort.flips: $@pancakeSort.flips + 1"1";
end flip
sink fixTop
@: 1;
2..$ -> #
$ -> \(when <~=$@fixTop> do $@fixTop -> !flip $ -> !flip \) -> !VOID
when <?($@pancakeSort.stack($) <$@pancakeSort.stack($@)..>)> do @: $;
end fixTop
$::length..2:-1 -> !fixTop
$@ !
end pancakeSort
 
[6,7,2,1,8,9,5,3,4] -> pancakeSort -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
[9, 8, 1, 2, 7, 6, 5, 3, 4]
[4, 3, 5, 6, 7, 2, 1, 8, 9]
[7, 6, 5, 3, 4, 2, 1, 8, 9]
[1, 2, 4, 3, 5, 6, 7, 8, 9]
[4, 2, 1, 3, 5, 6, 7, 8, 9]
[3, 1, 2, 4, 5, 6, 7, 8, 9]
[2, 1, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
{flips=8, stack=[1, 2, 3, 4, 5, 6, 7, 8, 9]}
</pre>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
# Some simple helper procedures
proc flip {nlist n} {
Line 2,751 ⟶ 3,712:
}
return $nlist
}</langsyntaxhighlight>
Demonstrate (with debug mode enabled so it prints intermediate states):
<langsyntaxhighlight lang="tcl">puts [pancakeSort {27916 5928 23535 14711 32184 14621 21093 14422 29844 11093} debug]</langsyntaxhighlight>
Output:
<pre>
Line 2,771 ⟶ 3,732:
</pre>
As you can see, it took 12 flips.
 
=={{header|Transd}}==
<syntaxhighlight lang="scheme">
#lang transd
 
MainModule: {
vint: [ 9, 0, 5, 10, 3, -3, -1, 8, -7, -4, -2, -6, 2, 4, 6, -10, 7, -8, -5, 1, -9],
_start: (λ (with n (- (size vint) 1) m 0
(textout vint "\n")
(while n
(= m (max-element-idx vint Range(0 (+ n 1))))
(if (neq m n)
(if m (reverse vint Range(0 (+ m 1))))
(reverse vint Range(0 (+ n 1))))
(-= n 1)
)
(textout vint "\n")
))
}</syntaxhighlight>{{out}}
<pre>
[9, 0, 5, 10, 3, -3, -1, 8, -7, -4, -2, -6, 2, 4, 6, -10, 7, -8, -5, 1, -9]
[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
</pre>
 
=={{header|uBasic/4tH}}==
{{trans|C}}
<syntaxhighlight lang="text">PRINT "Pancake sort:"
n = FUNC (_InitArray)
PROC _ShowArray (n)
Line 2,841 ⟶ 3,826:
PRINT
RETURN</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
{{works with|Bourne Again Shell}}
This takes advantage of the semi-standard UNIX utility <tt>shuf</tt> to randomize the initial array.
 
<syntaxhighlight lang="sh">#!/usr/bin/env bash
main() {
local stack
local -i n m i
if (( $# )); then
stack=("$@")
else
stack=($(printf '%s\n' {0..9} | shuf))
fi
print_stack 0 "${stack[@]}"
 
# start by looking at whole stack
(( n = ${#stack[@]} ))
 
# keep going until we're all sorted
while (( n > 0 )); do
 
# shrink the stack until its bottom is not the right size
while (( n > 0 && ${stack[n-1]} == n-1 )); do
(( n-=1 ))
done
 
# if we got to the top we're done
if (( n == 0 )); then
break
fi
 
# find the index of the largest pancake in the unsorted stack
m=0
for (( i=1; i < n-1; ++i )); do
if (( ${stack[i]} > ${stack[m]} )); then
(( m = i ))
fi
done
 
# if it's not on top, flip to get it there
if (( m > 0 )); then
stack=( $(flip "$(( m + 1 ))" "${stack[@]}") )
print_stack "$(( m + 1))" "${stack[@]}"
fi
 
# now flip the top to the bottom
stack=( $(flip "$n" "${stack[@]}" ) )
print_stack "$n" "${stack[@]}"
 
# and move up
(( n -= 1 ))
done
print_stack 0 "${stack[@]}"
}
 
# display the stack, optionally with brackets around a prefix
print_stack() {
local prefix=$1
shift
if (( prefix )); then
printf '[%s' "$1"
if (( prefix > 1 )); then
printf ',%s' "${@:2:prefix-1}"
fi
printf ']'
else
printf ' '
fi
if (( prefix < $# )); then
printf '%s' "${@:prefix+1:1}"
if (( prefix+1 < $# )); then
printf ',%s' "${@:prefix+2:$#-prefix-1}"
fi
fi
printf '\n'
}
 
# reverse the first N elements of an array
flip() {
local -i size end midpoint i
local stack temp
size=$1
shift
stack=( "$@" )
if (( size > 1 )); then
(( end = size - 1 ))
(( midpoint = size/2 + size % 2 ))
for (( i=0; i<midpoint; ++i )); do
temp=${stack[i]}
stack[i]=${stack[size-1-i]}
stack[size-1-i]=$temp
done
fi
printf '%s\n' "${stack[@]}"
}
 
main "$@"</syntaxhighlight>
 
{{Out}}
Sample run:
<pre> 3,0,9,7,6,1,2,5,4,8
[9,0,3]7,6,1,2,5,4,8
[8,4,5,2,1,6,7,3,0,9]
[0,3,7,6,1,2,5,4,8]9
[7,3,0]6,1,2,5,4,8,9
[4,5,2,1,6,0,3,7]8,9
[6,1,2,5,4]0,3,7,8,9
[3,0,4,5,2,1,6]7,8,9
[5,4,0,3]2,1,6,7,8,9
[1,2,3,0,4,5]6,7,8,9
[3,2,1]0,4,5,6,7,8,9
[0,1,2,3]4,5,6,7,8,9
0,1,2,3,4,5,6,7,8,9</pre>
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">
<lang vb>
 
'pancake sort
Line 2,911 ⟶ 4,011:
printarray A
End Sub
</syntaxhighlight>
</lang>
 
Sample output:
Line 2,940 ⟶ 4,040:
Final array:
0 1 3 5 7 8 9 10 23 50
</pre>
 
=={{header|Wren}}==
{{trans|Go}}
{{libheader|Wren-sort}}
<syntaxhighlight lang="wren">import "./sort" for Find
 
class Pancake {
construct new(a) {
_a = a.toList
}
 
flip(r) {
for (l in 0...r) {
_a.swap(r, l)
r = r - 1
}
}
 
sort() {
for (uns in _a.count-1..1) {
var h = Find.highest(_a[0..uns])
var lx = h[2][0]
flip(lx)
flip(uns)
}
}
 
toString { _a.toString }
}
 
var p = Pancake.new([31, 41, 59, 26, 53, 58, 97, 93, 23, 84])
System.print("unsorted: %(p)")
p.sort()
System.print("sorted : %(p)")</syntaxhighlight>
 
{{out}}
<pre>
unsorted: [31, 41, 59, 26, 53, 58, 97, 93, 23, 84]
sorted : [23, 26, 31, 41, 53, 58, 59, 84, 93, 97]
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang "XPL0">proc Show(A, N); \Show items in array A with size N
int A, N, I;
[for I:= 0 to N-1 do
[IntOut(0, A(I)); ChOut(0, ^ )];
CrLf(0);
];
 
proc Sort(A, N); \Pancake sort array A with size N
int A, N, I, J, JMax;
 
proc Flip(K); \Reverse order of array items from 0 to K
int K, L, T;
[L:= 0;
while L < K do
[T:= A(L); A(L):= A(K); A(K):= T; \swap
K:= K-1;
L:= L+1;
];
Show(A, N); \show result of reversed items
];
 
[for I:= N-1 downto 1 do
[JMax:= 0;
for J:= 1 to I do
if A(J) > A(JMax) then JMax:= J;
if JMax < I then
[Flip(JMax);
Flip(I);
];
];
];
 
int A, N;
[A:= [6, 7, 2, 1, 8, 9, 5, 3, 4];
N:= 9;
Show(A, N); \show initial
Sort(A, N);
]</syntaxhighlight>
{{out}}
<pre>
6 7 2 1 8 9 5 3 4
9 8 1 2 7 6 5 3 4
4 3 5 6 7 2 1 8 9
7 6 5 3 4 2 1 8 9
1 2 4 3 5 6 7 8 9
4 2 1 3 5 6 7 8 9
3 1 2 4 5 6 7 8 9
3 1 2 4 5 6 7 8 9
2 1 3 4 5 6 7 8 9
2 1 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
</pre>
 
=={{header|zkl}}==
{{trans|Julia}}
<langsyntaxhighlight lang="zkl">fcn pancakeSort(a){
foreach i in ([a.len()-1..1,-1]){
j := a.index((0).max(a[0,i+1])); // min for decending sort
Line 2,950 ⟶ 4,144:
}
a
}</langsyntaxhighlight>
Note: [offset,count] not [start,stop]
 
Finding the max index creates a partial list, which isn't good; if it matters use:
<langsyntaxhighlight lang="zkl"> j := (i+1).reduce('wrap(x,y){ if(a[x]>a[y]) x else y });</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">pancakeSort(List(7,6,9,2,4,8,1,3,5)).println();</langsyntaxhighlight>
{{out}}<pre>L(1,2,3,4,5,6,7,8,9)</pre>
 
9,476

edits