Sorting algorithms/Pancake sort: Difference between revisions
m
→{{header|Wren}}: Minor tidy
m (→{{header|REXX}}: added an optimization.) |
m (→{{header|Wren}}: Minor tidy) |
||
(13 intermediate revisions by 8 users not shown) | |||
Line 31:
{{trans|Python}}
<
F pancakesort(&data)
Line 54:
print(‘Original List: ’data.join(‘ ’))
pancakesort(&data)
print(‘Pancake Sorted List: ’data.join(‘ ’))</
{{out}}
Line 74:
=={{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 */
Line 292:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
<pre>
Value : -5
Line 308:
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}}==
<
procedure Pancake_Sort is
generic
Line 356 ⟶ 454:
end loop;
Ada.Text_IO.New_Line;
end Pancake_Sort;</
Output:
Line 363 ⟶ 461:
=={{header|ALGOL 68}}==
{{trans|Euphoria}}
<
BEGIN
[UPB s]INT ss := s;
Line 404 ⟶ 502:
printf (($"unsorted: "10(g(4) )l$, s));
printf (($"sorted: "10(g(4) )l$, pancake sort(s)))
</syntaxhighlight>
{{out}}
<pre>Pancake sort demonstration
Line 414 ⟶ 512:
Algorithm gleaned from [[Sorting_algorithms/Pancake_sort#Phix|Phix]] and that from [[Sorting_algorithms/Pancake_sort#Euphoria|Euphoria]]
<
script o
property lst : aList
Line 466 ⟶ 564:
set output to "Before: {" & pre & ("}" & linefeed & "After: {" & post & "}")
set AppleScript's text item delimiters to astid
return output</
{{output}}
<
After: {3, 11, 12, 18, 23, 23, 26, 27, 38, 39, 40, 40, 41, 43, 58, 59, 69, 72, 74, 91}"</
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program pancakeSort.s */
Line 675 ⟶ 773:
.include "../affichage.inc"
</syntaxhighlight>
=={{header|Arturo}}==
<
arr: new items
len: size arr
Line 696 ⟶ 794:
]
print pancakeSort [3 1 2 8 5 7 9 4 6]</
{{out}}
Line 703 ⟶ 801:
=={{header|AutoHotkey}}==
<
Loop { ; test loop
;---------------------------------------------------------------------------
Line 752 ⟶ 850:
Return, List
}
</syntaxhighlight>
=={{header|BASIC}}==
Line 758 ⟶ 856:
{{works with|QBasic}}
<
DIM nums(9) AS INTEGER
Line 803 ⟶ 901:
PRINT
END IF
NEXT</
Sample output:
Line 824 ⟶ 922:
This is a graphical variation of the above.
<
CONST delay = .1 'controls display speed
Line 878 ⟶ 976:
ttmp = TIMER
DO WHILE TIMER < ttmp + delay: LOOP
RETURN</
Sample output:
Line 886 ⟶ 984:
=={{header|Batch File}}==
{{trans|BASIC}}
<
:: Batch File Implementation
Line 962 ⟶ 1,060:
echo DONE^^!
exit /b 0</
{{Out}}
<pre>Initial Sequence:
Line 988 ⟶ 1,086:
=={{header|BBC BASIC}}==
<
test() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1
PROCpancakesort(test())
Line 1,019 ⟶ 1,117:
SWAP a(i%), a(n%-i%)
NEXT
ENDPROC</
'''Output:'''
<pre>
Line 1,027 ⟶ 1,125:
=={{header|C}}==
'''The function that sorts:'''
<
{
//If it's less than 2 long, just return it as sorting isn't really needed...
Line 1,068 ⟶ 1,166:
return moves;
}</
Where do_flip() is a simple function to flip a part of an array:
<
{
int swap;
Line 1,081 ⟶ 1,179:
list[num]=swap;
}
}</
'''Testing the function:'''
<
{
//Just need some random numbers. I chose <100
Line 1,103 ⟶ 1,201:
print_array(list, 9);
printf(" - with a total of %d moves\n", moves);
}</
=={{header|C sharp|C#}}==
<
public static class PancakeSorter
{
Line 1,148 ⟶ 1,246:
}
}
</syntaxhighlight>
=={{header|C++}}==
<
#include <iostream>
#include <iterator>
Line 1,200 ⟶ 1,298:
std::copy(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}</
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 </pre>
=={{header|Clojure}}==
<
(defn pancake-sort
[arr]
Line 1,215 ⟶ 1,313:
head (reverse torev)]
(cons mx (pancake-sort (concat (drop 1 head) (drop 1 tail))))))))
</syntaxhighlight>
=={{header|Common Lisp}}==
<
"A destructive version of Pancake Sort that works with either lists or arrays of numbers."
(defun flip (lst index)
Line 1,228 ⟶ 1,326:
(flip lst (1+ index)))
(flip lst i)
finally (return (coerce lst (type-of seq)))))</
Output:
<
(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)</
=={{header|D}}==
{{trans|Python}}
<
void pancakeSort(bool tutor=false, T)(T[] data) {
Line 1,262 ⟶ 1,360:
data.pancakeSort!true;
data.writeln;
}</
{{out}}
<pre>With: 769248135 doflip 3
Line 1,279 ⟶ 1,377:
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
class
PANCAKE_SORT [G -> COMPARABLE]
Line 1,385 ⟶ 1,483:
end
</syntaxhighlight>
Test:
<syntaxhighlight lang="eiffel">
class
APPLICATION
Line 1,421 ⟶ 1,519:
end
</syntaxhighlight>
{{out}}
<pre>
Line 1,431 ⟶ 1,529:
ELENA 5.0 :
{{trans|C#}}
<
extension op
Line 1,497 ⟶ 1,595:
console.printLine("before:", list.asEnumerable());
console.printLine("after :", list.pancakeSort().asEnumerable())
}</
{{out}}
<pre>
Line 1,505 ⟶ 1,603:
=={{header|Elixir}}==
<
def pancake_sort(list) when is_list(list), do: pancake_sort(list, length(list))
Line 1,531 ⟶ 1,629:
IO.inspect list = Enum.shuffle(1..9)
IO.inspect Sort.pancake_sort(list)</
{{out}}
Line 1,540 ⟶ 1,638:
=={{header|Euphoria}}==
<
object temp
for i = 1 to n/2 do
Line 1,573 ⟶ 1,671:
? s
? pancake_sort(s)</
Output:
Line 1,581 ⟶ 1,679:
=={{header|F_Sharp|F#}}==
<
let show data = data |> Array.iter (printf "%d ") ; printfn ""
Line 1,599 ⟶ 1,697:
loop partialSort (limit-1)
loop items ((Array.length items)-1)</
Usage: pancakeSort [|31; 41; 59; 26; 53; 58; 97; 93; 23; 84|] |> show
Line 1,609 ⟶ 1,707:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
implicit none
Line 1,645 ⟶ 1,743:
end subroutine
end program Pancake_Demo</
Output:
<pre>
Line 1,664 ⟶ 1,762:
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
' for boundry checks on array's compile with: fbc -s console -exx
Line 1,767 ⟶ 1,865:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>unsorted -1 -4 1 6 7 5 2 -3 4 -5 -2 -6 0 3 -7
Line 1,788 ⟶ 1,886:
=={{header|Go}}==
<
import "fmt"
Line 1,821 ⟶ 1,919:
a[l], a[r] = a[r], a[l]
}
}</
Output:
<pre>
Line 1,830 ⟶ 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.
<
def flip = { list, n -> (0..<((n+1)/2)).each { makeSwap(list, it, n-it) } }
Line 1,845 ⟶ 1,943:
}
list
}</
Test:
<
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,856 ⟶ 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]))</
The use of decimals and integers that compare as equal demonstrates, but of course not '''prove''', that the sort is stable.
Line 1,871 ⟶ 1,969:
=={{header|Haskell}}==
<
import Control.Arrow
import Control.Monad
Line 1,884 ⟶ 1,982:
dopcs ([],rs) = rs
dopcs ([x],rs) = x:rs
dopcs (xs,rs) = dopcs $ (init &&& (:rs).last ) $ dblflipIt xs</
Example:
<
[0,1,2,2,3]</
=={{header|Haxe}}==
<
@:generic
inline private static function flip<T>(arr:Array<T>, num:Int) {
Line 1,937 ⟶ 2,035:
Sys.println('Sorted Strings: ' + stringArray);
}
}</
{{out}}
Line 1,950 ⟶ 2,048:
=={{header|Icon}} and {{header|Unicon}}==
<
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,990 ⟶ 2,088:
every writes(" ["|right(!X,4)|" ]\n") # show X
return X
end</
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 2,019 ⟶ 2,117:
=={{header|J}}==
{{eff note|J|/:~}}
<
unsorted=: #~ 1 , [: >./\. 2 >/\ ]
FlDown=: flip 1 + (i. >./)@unsorted
FlipUp=: flip 1 >. [:+/>./\&|.@(< {.)
pancake=: FlipUp@FlDown^:_</
Example use:
<
1 0 8 7 4 6 3 5 2
0 1 2 3 4 5 6 7 8</
See the [[Talk:Sorting_algorithms/Pancake_sort#J_implementation|discussion page]] for illustrations of the other words.
Line 2,036 ⟶ 2,134:
=={{header|Java}}==
<
public class PancakeSort
{
Line 2,118 ⟶ 2,216:
System.out.println(pancakes);
}
}</
Example:
<
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 2,136 ⟶ 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 </
===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}}==
<
for (var i = this.length - 1; i >= 1; i--) {
// find the index of the largest element not yet sorted
Line 2,171 ⟶ 2,319:
}
ary = [7,6,5,9,8,4,3,1,2,0]
sorted = ary.concat().pancake_sort();</
=={{header|jq}}==
{{works with|jq|1.4}}
This version skips the pair of flips if the focal item is already in place.
<
def flip(i):
Line 2,197 ⟶ 2,345:
| if ($i == $max) then .
else flip($max) | flip($i)
end ) ;</
'''Example''':
<
| pancakeSort</
{{out}}
<
[null,0,0.5,1,1,2,3,[1],[2],{"a":2},{"b":1}]</
=={{header|Julia}}==
<syntaxhighlight lang="julia">function pancakesort!(arr::Vector{<:Real})
len = length(arr)
if len < 2 return arr end
for i in len:-1:2
j =
if i == j continue end
arr[1:j] = reverse(arr[1:j])
Line 2,222 ⟶ 2,368:
v = rand(-10:10, 10)
println("# unordered: $v\n -> ordered: ", pancakesort!(v))</
{{out}}
Line 2,229 ⟶ 2,375:
=={{header|Kotlin}}==
<
/** Returns the index of the highest number in the range 0 until n. */
fun indexOfMax(n: Int): Int = (0 until n).maxByOrNull{ a[it] }!!
Line 2,255 ⟶ 2,401:
println("${a.contentToString()} initially")
pancakeSort(a)
}</
{{out}}
Line 2,275 ⟶ 2,421:
=={{header|Lua}}==
<
math.randomseed(os.time())
numList = {step = 0, sorted = 0}
Line 2,340 ⟶ 2,486:
numList:show()
until numList:isSorted()
</syntaxhighlight>
{{out}}
<pre>Initial state: -67 61 80 47 21 74 43 22 66 -66
Line 2,361 ⟶ 2,507:
=={{header|Maple}}==
<
local start, temp, icopy;
temp, start, icopy := 0,1,i:
Line 2,390 ⟶ 2,536:
end do:
print(arr);
end proc:</
{{Out|Example}}
Input: arr := Array([17,3,72,0,36,2,3,8,40,1]):
Line 2,405 ⟶ 2,551:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
LMaxPosition[a_, n_] := With[{b = Take[a, n]}, First[Ordering[b, -1]]]
SetAttributes[Flip, HoldAll];
Line 2,421 ⟶ 2,567:
a
]
pancakeSort[{6, 7, 8, 9, 2, 5, 3, 4, 1}]</
{{out}}
<pre>{9,8,7,6,2,5,3,4,1}
Line 2,433 ⟶ 2,579:
=={{header|MATLAB}} / {{header|Octave}}==
<
for i = (numel(list):-1:2)
Line 2,460 ⟶ 2,606:
end
end %for
end %pancakeSort</
Sample Usage:
<
ans =
6 5 4 3 2 1</
=={{header|MAXScript}}==
<
(
local new = #()
Line 2,498 ⟶ 2,644:
return arr
)
)</
Output:
<syntaxhighlight 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>
=={{header|NetRexx}}==
Sorts integers, decimal numbers and strings because they're all the same to NetRexx.
<
options replace format comments java crossref symbols nobinary
Line 2,590 ⟶ 2,736:
return clist
</syntaxhighlight>
{{out}}
<pre>
Line 2,613 ⟶ 2,759:
=={{header|Nim}}==
<
proc pancakeSort[T](list: var openarray[T]) =
Line 2,638 ⟶ 2,784:
var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]
pancakeSort a
echo a</
Output:
<pre>@[-31, 0, 2, 2, 4, 65, 83, 99, 782]</pre>
=={{header|OCaml}}==
<
| [] -> (true)
| x::y::_ when x > y -> (false)
Line 2,685 ⟶ 2,831:
print_list res;
Printf.printf " sorted in %d loops\n" n;
;;</
=={{header|PARI/GP}}==
<
my(top=#v);
while(top>1,
Line 2,707 ⟶ 2,853:
);
v
};</
=={{header|Pascal}}==
<
procedure flip(var b: array of integer; last: integer);
Line 2,774 ⟶ 2,920:
end;
writeln;
end.</
Output:
<pre>:>./PancakeSort
Line 2,784 ⟶ 2,930:
=={{header|Perl}}==
<
my @x = @_;
for my $idx (0 .. $#x - 1) {
Line 2,802 ⟶ 2,948:
@a = pancake(@a);
print "After @a\n";
</syntaxhighlight>
Sample output:
<pre>Before 57 37 35 35 22 58 70 53 77 15
Line 2,808 ⟶ 2,954:
=={{header|Phix}}==
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 2,828 ⟶ 2,974:
<span style="color: #0000FF;">?</span> <span style="color: #000000;">s</span>
<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>
<!--</
{{out}}
<pre>
Line 2,834 ⟶ 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}}==
<
(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))) ) ) )</
Output:
<pre>: (trace 'flip)
Line 2,864 ⟶ 3,039:
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
pancake_sort: procedure options (main); /* 23 April 2009 */
declare a(10) fixed, (i, n, loc) fixed binary;
Line 2,900 ⟶ 3,075:
end pancake_sort;
</syntaxhighlight>
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,913 ⟶ 3,088:
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
</syntaxhighlight>
=={{header|PowerShell}}==
<
{
$data=$indata.Clone()
Line 2,953 ⟶ 3,128:
}
$l = 100; PancakeSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( 0, $l - 1 ) } )</
=={{header|PureBasic}}==
<
Define i, j, k, Loops
Dim Pile(9)
Line 2,999 ⟶ 3,174:
Print(#CRLF$+#CRLF$+"Press ENTER to quit."): Input()
CloseConsole()
EndIf</
'''Output can look like
Line 3,010 ⟶ 3,185:
=={{header|Python}}==
'''The function:'''
<
def pancakesort(data):
Line 3,029 ⟶ 3,204:
% ( ' '.join(str(x) for x in data), size ))
data[:size] = reversed(data[:size])
if tutor: print()</
'''A test:'''
<
import random
Line 3,041 ⟶ 3,216:
print('Original List: %r' % ' '.join(data))
pancakesort(data)
print('Pancake Sorted List: %r' % ' '.join(data))</
'''Sample output:'''
Line 3,058 ⟶ 3,233:
=={{header|Quackery}}==
<
[ 0 swap behead swap
Line 3,071 ⟶ 3,246:
[ dup i^ split nip
smallest i^ + flip
i^ flip ] ] is pancakesort ( [ --> [ )</
'''Testing in Quackery shell:'''
Line 3,085 ⟶ 3,260:
=={{header|Racket}}==
<
#lang racket
Line 3,098 ⟶ 3,273:
(pancake-sort (shuffle (range 0 10)))
;; => '(0 1 2 3 4 5 6 7 8 9)
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
my $endpoint = @a.end;
while $endpoint > 0 and not [<] @a {
Line 3,122 ⟶ 3,297:
say 'input = ' ~ @data;
say 'output = ' ~ @data.&pancake_sort;
</syntaxhighlight>
Output:<pre>input = 6 7 2 1 8 9 5 3 4
Line 3,129 ⟶ 3,304:
=={{header|REXX}}==
<
call gen /*generate elements in the @. array.*/
call show 'before sort' /*display the BEFORE array elements.*/
Line 3,159 ⟶ 3,334:
end /*j*/
call panFlip ?; call panFlip n
end /*n*/; return</
{{out|output|text= when using the internally generated numbers:}}
Line 3,250 ⟶ 3,425:
=={{header|Ring}}==
<
pancakeList = [6, 7, 8, 9, 2, 5, 3, 4, 1]
flag = 0
Line 3,280 ⟶ 3,455:
end
return A
</syntaxhighlight>
Output:
<pre>
Line 3,290 ⟶ 3,465:
=={{header|Ruby}}==
<
def pancake_sort!
num_flips = 0
Line 3,311 ⟶ 3,486:
p a = (1..9).to_a.shuffle
p a.pancake_sort!</
'''sample output:'''
Line 3,328 ⟶ 3,503:
=={{header|Rust}}==
<
let len = v.len();
// trivial case -- no flips
Line 3,369 ⟶ 3,544:
pancake_sort(&mut strings);
println!("After: {:?}", strings);
}</
=={{header|Sidef}}==
{{trans|Perl}}
<
for idx in ^(a.end) {
var min = idx
Line 3,386 ⟶ 3,561:
var arr = 10.of{ 100.irand }
say "Before: #{arr}"
say "After: #{pancake(arr)}"</
{{out}}
Line 3,396 ⟶ 3,571:
=={{header|Swift}}==
{{trans|Java}}
<
struct PancakeSort {
Line 3,461 ⟶ 3,636:
var a = PancakeSort(arr: arr)
a.sort(arr.count, dir: 1)
println(a.arr)</
{{out}}
<pre>
Line 3,479 ⟶ 3,654:
=={{header|Tailspin}}==
Simplest version, bubblesort style
<
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
Line 3,499 ⟶ 3,674:
[6,7,2,1,8,9,5,3,4] -> pancakeSort -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
Line 3,514 ⟶ 3,689:
=={{header|Tcl}}==
<
# Some simple helper procedures
proc flip {nlist n} {
Line 3,537 ⟶ 3,712:
}
return $nlist
}</
Demonstrate (with debug mode enabled so it prints intermediate states):
<
Output:
<pre>
Line 3,559 ⟶ 3,734:
=={{header|Transd}}==
<
#lang transd
Line 3,576 ⟶ 3,751:
(textout vint "\n")
))
}</
<pre>
[9, 0, 5, 10, 3, -3, -1, 8, -7, -4, -2, -6, 2, 4, 6, -10, 7, -8, -5, 1, -9]
Line 3,584 ⟶ 3,759:
=={{header|uBasic/4tH}}==
{{trans|C}}
<syntaxhighlight lang="text">PRINT "Pancake sort:"
n = FUNC (_InitArray)
PROC _ShowArray (n)
Line 3,651 ⟶ 3,826:
PRINT
RETURN</
=={{header|UNIX Shell}}==
Line 3,657 ⟶ 3,832:
This takes advantage of the semi-standard UNIX utility <tt>shuf</tt> to randomize the initial array.
<
main() {
local stack
Line 3,749 ⟶ 3,924:
}
main "$@"</
{{Out}}
Line 3,768 ⟶ 3,943:
=={{header|VBA}}==
<syntaxhighlight lang="vb">
'pancake sort
Line 3,836 ⟶ 4,011:
printarray A
End Sub
</syntaxhighlight>
Sample output:
Line 3,870 ⟶ 4,045:
{{trans|Go}}
{{libheader|Wren-sort}}
<
class Pancake {
Line 3,879 ⟶ 4,054:
flip(r) {
for (l in 0...r) {
r = r - 1
}
Line 3,901 ⟶ 4,074:
System.print("unsorted: %(p)")
p.sort()
System.print("sorted : %(p)")</
{{out}}
Line 3,907 ⟶ 4,080:
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}}
<
foreach i in ([a.len()-1..1,-1]){
j := a.index((0).max(a[0,i+1])); // min for decending sort
Line 3,917 ⟶ 4,144:
}
a
}</
Note: [offset,count] not [start,stop]
Finding the max index creates a partial list, which isn't good; if it matters use:
<
<
{{out}}<pre>L(1,2,3,4,5,6,7,8,9)</pre>
|