Sorting algorithms/Permutation sort: Difference between revisions

m
(Added Quackery.)
m (→‎{{header|Wren}}: Minor tidy)
 
(4 intermediate revisions by 4 users not shown)
Line 14:
<br><br>
=={{header|11l}}==
<langsyntaxhighlight lang="11l">F is_sorted(arr)
L(i) 1..arr.len-1
I arr[i-1] > arr[i]
Line 26:
V arr = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]
permutation_sort(&arr)
print(arr)</langsyntaxhighlight>
 
{{out}}
Line 35:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program permutationSort64.s */
Line 279:
.include "../includeARM64.inc"
 
</syntaxhighlight>
</lang>
<pre>
Value : -5
Line 297:
 
=={{header|ActionScript}}==
<langsyntaxhighlight ActionScriptlang="actionscript">//recursively builds the permutations of permutable, appended to front, and returns the first sorted permutation it encounters
function permutations(front:Array, permutable:Array):Array {
//If permutable has length 1, there is only one possible permutation. Check whether it's sorted
Line 327:
function permutationSort(array:Array):Array {
return permutations([],array);
}</langsyntaxhighlight>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program permutationSort.s */
Line 516:
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">sorted?: function [arr][
previous: first arr
 
Line 536:
]
 
print permutationSort [3 1 2 8 5 7 9 4 6]</langsyntaxhighlight>
 
{{out}}
Line 544:
=={{header|AutoHotkey}}==
ahk forum: [http://www.autohotkey.com/forum/post-276680.html#276680 discussion]
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % PermSort("")
MsgBox % PermSort("xxx")
MsgBox % PermSort("3,2,1")
Line 586:
While i < j
t := %v%%i%, %v%%i% := %v%%j%, %v%%j% := t, ++i, --j
}</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> DIM test(9)
test() = 4, 65, 2, 31, 0, 99, 2, 83, 782, 1
Line 633:
IF d(I%) < d(I%-1) THEN = FALSE
NEXT
= TRUE</langsyntaxhighlight>
{{out}}
<pre>
Line 641:
=={{header|C}}==
Just keep generating [[wp:Permutation#Systematic_generation_of_all_permutations|next lexicographic permutation]] until the last one; it's sorted by definition.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 686:
printf("%s\n", strs[i]);
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight Clang="c sharp|Cc#">
public static class PermutationSorter
{
Line 730:
}
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
Since <tt>next_permutation</tt> already returns whether the resulting sequence is sorted, the code is quite simple:
 
<langsyntaxhighlight lang="cpp">#include <algorithm>
 
template<typename ForwardIterator>
Line 744:
// -- this block intentionally left empty --
}
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
 
<langsyntaxhighlight lang="lisp">
(use '[clojure.contrib.combinatorics :only (permutations)])
 
Line 755:
 
(permutation-sort [2 3 5 3 5])
</syntaxhighlight>
</lang>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript"># This code takes a ridiculously inefficient algorithm and rather futilely
# optimizes one part of it. Permutations are computed lazily.
 
Line 818:
console.log 'DONE!'
console.log 'sorted copy:', ans
</syntaxhighlight>
</lang>
{{out}}
<syntaxhighlight lang="text">
> coffee permute_sort.coffee
input: [ 'c', 'b', 'a', 'd' ]
Line 840:
DONE!
sorted copy: [ 'a', 'b', 'c', 'd' ]
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
Line 848:
The <code>nth-permutation</code> function is some classic algorithm from Wikipedia.
 
<langsyntaxhighlight lang="lisp">(defun factorial (n)
(loop for result = 1 then (* i result)
for i from 2 to n
Line 881:
for permutation = (nth-permutation i sequence)
when (sortedp fn permutation)
do (return permutation)))</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lisp">CL-USER> (time (permutation-sort #'> '(8 3 10 6 1 9 7 2 5 4)))
Evaluation took:
5.292 seconds of real time
Line 892:
611,094,240 bytes consed
(1 2 3 4 5 6 7 8 9 10)</langsyntaxhighlight>
 
=={{header|Crystal}}==
<langsyntaxhighlight lang="crystal">def sorted?(items : Array)
prev = items[0]
items.each do |item|
Line 912:
end
end
end</langsyntaxhighlight>
 
=={{header|D}}==
===Basic Version===
This uses the second (lazy) permutations from the Permutations Task.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, permutations2;
 
void permutationSort(T)(T[] items) pure nothrow @safe @nogc {
Line 929:
data.permutationSort;
data.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</pre>
Line 936:
===Alternative Version===
{{trans|C++}}
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm;
 
void permutationSort(T)(T[] items) pure nothrow @safe @nogc {
Line 946:
data.permutationSort;
data.writeln;
}</langsyntaxhighlight>
The output is the same.
Run-time about 1.04 seconds with ldc2 (the C++ entry with G++ takes about 0.4 seconds).
Line 953:
{{trans|C++}}
 
<langsyntaxhighlight lang="e">def swap(container, ixA, ixB) {
def temp := container[ixA]
container[ixA] := container[ixB]
Line 992:
def permutationSort(flexList) {
while (nextPermutation(flexList)) {}
}</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
;; This efficient sort method uses the list library for permutations
 
Line 1,013:
 
→ (0 1 2 3 4 5)
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Sort do
def permutation_sort([]), do: []
def permutation_sort(list) do
Line 1,033:
 
IO.inspect list = for _ <- 1..9, do: :rand.uniform(20)
IO.inspect Sort.permutation_sort(list)</langsyntaxhighlight>
 
{{out}}
Line 1,039:
[18, 2, 19, 10, 17, 10, 14, 8, 3]
[2, 3, 8, 10, 10, 14, 17, 18, 19]
</langpre>
 
=={{header|EMal}}==
{{trans|Java}}
<syntaxhighlight lang="emal">
type PermutationSort
fun isSorted = logic by List a
for int i = 1; i < a.length; ++i
if a[i - 1] > a[i] do return false end
end
return true
end
fun permute = void by List a, int n, List lists
if n == 1
List b = int[]
for int i = 0; i < a.length; ++i
b.append(a[i])
end
lists.append(b)
return
end
int i = 0
while i < n
a.swap(i, n - 1)
permute(a, n - 1, lists)
a.swap(i, n - 1)
i = i + 1
end
end
fun sort = List by List a
List lists = List[]
permute(a, a.length, lists)
for each List list in lists
if isSorted(list) do return list end
end
return a
end
type Main
List a = int[3,2,1,8,9,4,6]
writeLine("Unsorted: " + a)
a = PermutationSort.sort(a)
writeLine(" Sorted: " + a)
</syntaxhighlight>
{{out}}
<pre>
Unsorted: [3,2,1,8,9,4,6]
Sorted: [1,2,3,4,6,8,9]
</pre>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: grouping io math.combinatorics math.order prettyprint ;
IN: rosetta-code.permutation-sort
 
Line 1,049 ⟶ 1,096:
{ 10 2 6 8 1 4 3 } permutation-sort .
"apple" permutation-sort print</langsyntaxhighlight>
{{out}}
<pre>
Line 1,057 ⟶ 1,104:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 07-04-2017
' compile with: fbc -s console
 
Line 1,115 ⟶ 1,162:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>unsorted array
Line 1,127 ⟶ 1,174:
=={{header|Go}}==
Not following the pseudocode, it seemed simpler to just test sorted at the bottom of a recursive permutation generator.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,165 ⟶ 1,212:
}
return false
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Line 1,171 ⟶ 1,218:
 
I believe that this method of constructing permutations results in a stable sort, but I have not actually proven that assertion.
<langsyntaxhighlight lang="groovy">def factorial = { (it > 1) ? (2..it).inject(1) { i, j -> i*j } : 1 }
 
def makePermutation;
Line 1,192 ⟶ 1,239:
def pIndex = (0..<fact).find { print "."; sorted(permuteA(it)) }
permuteA(pIndex)
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">println permutationSort([7,0,12,-45,-1])
println ()
println permutationSort([10, 10.0, 10.00, 1])
Line 1,202 ⟶ 1,249:
println permutationSort([10.0, 10.00, 10, 1])
println permutationSort([10.00, 10, 10.0, 1])
println permutationSort([10.00, 10.0, 10, 1])</langsyntaxhighlight>
The examples with distinct integer and decimal values that compare as equal are there to demonstrate, but not to prove, that the sort is stable.
 
Line 1,216 ⟶ 1,263:
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">import Control.Monad
 
permutationSort l = head [p | p <- permute l, sorted p]
Line 1,227 ⟶ 1,274:
insert e [] = return [e]
insert e l@(h : t) = return (e : l) `mplus`
do { t' <- insert e t ; return (h : t') }</langsyntaxhighlight>
{{works with|GHC|6.10}}
<langsyntaxhighlight lang="haskell">import Data.List (permutations)
 
permutationSort l = head [p | p <- permutations l, sorted p]
 
sorted (e1 : e2 : r) = e1 <= e2 && sorted (e2 : r)
sorted _ = True</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Partly from [http://infohost.nmt.edu/tcc/help/lang/icon/backtrack.html here]
<langsyntaxhighlight lang="icon">procedure do_permute(l, i, n)
if i >= n then
return l
Line 1,258 ⟶ 1,305:
l := [6,3,4,5,1]
|( l := permute(l) & sorted(l)) \1 & every writes(" ",!l)
end</langsyntaxhighlight>
 
=={{header|J}}==
{{eff note|J|/:~}}
A function to locate the permuation index, in the naive manner prescribed by the task:
<langsyntaxhighlight lang="j">ps =:(1+])^:((-.@-:/:~)@A.~)^:_ 0:</langsyntaxhighlight>
Of course, this can be calculated much more directly (and efficiently):
<langsyntaxhighlight lang="j">ps =: A.@:/:</langsyntaxhighlight>
Either way:
<langsyntaxhighlight lang="j"> list =: 2 7 4 3 5 1 0 9 8 6
ps list
Line 1,276 ⟶ 1,323:
(A.~ps) list
0 1 2 3 4 5 6 7 8 9</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java5">import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
Line 1,330 ⟶ 1,377:
arr[j]=temp;
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,341 ⟶ 1,388:
'''Infrastructure''':
The following function generates a stream of permutations of an arbitrary JSON array:
<langsyntaxhighlight lang="jq">def permutations:
if length == 0 then []
else
Line 1,348 ⟶ 1,395:
| ($in|del(.[$i])|permutations)
| [$in[$i]] + .
end ;</langsyntaxhighlight>
 
Next is a generic function for checking whether the input array is non-decreasing.
If your jq has until/2 then its definition here can be removed.
<langsyntaxhighlight lang="jq">def sorted:
def until(cond; next):
def _until: if cond then . else (next|_until) end;
Line 1,361 ⟶ 1,408:
else . as $in
| 1 | until( . == $length or $in[.-1] > $in[.] ; .+1) == $length
end;</langsyntaxhighlight>
 
'''Permutation-sort''':
Line 1,370 ⟶ 1,417:
 
{{works with|jq|1.4}}
<langsyntaxhighlight lang="jq">def permutation_sort_slow:
reduce permutations as $p (null; if . then . elif ($p | sorted) then $p else . end);</langsyntaxhighlight>
 
{{works with|jq|with foreach}}
<langsyntaxhighlight lang="jq">def permutation_sort:
# emit the first item in stream that satisfies the condition
def first(stream; cond):
Line 1,382 ⟶ 1,429:
if .[0] then break $out else [($item | cond), $item] end;
if .[0] then .[1] else empty end );
first(permutations; sorted);</langsyntaxhighlight>
 
'''Example''':
<langsyntaxhighlight lang="jq">["too", true, 1, 0, {"a":1}, {"a":0} ] | permutation_sort</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -c -n -f Permutation_sort.jq
[true,0,1,"too",{"a":0},{"a":1}]</langsyntaxhighlight>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia"># v0.6
 
using Combinatorics
Line 1,404 ⟶ 1,451:
 
x = randn(10)
@show x permsort(x)</langsyntaxhighlight>
 
{{out}}
Line 1,411 ⟶ 1,458:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun <T : Comparable<T>> isSorted(list: List<T>): Boolean {
Line 1,459 ⟶ 1,506:
val output2 = permutationSort(input2)
println("After sorting : $output2")
}</langsyntaxhighlight>
 
{{out}}
Line 1,471 ⟶ 1,518:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">-- Return an iterator to produce every permutation of list
function permute (list)
local function perm (list, n)
Line 1,500 ⟶ 1,547:
list = nextPermutation() --/ for p in permute(list) do
end --/ stuffWith(p)
print(unpack(list)) --/ end</langsyntaxhighlight>
{{out}}
<pre>1 2 3</pre>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">arr := Array([17,0,-1,72,0]):
len := numelems(arr):
P := Iterator:-Permute(len):
Line 1,514 ⟶ 1,561:
break:
end if:
end do:</langsyntaxhighlight>
{{Out|Output}}
<pre>[-1,0,0,17,72]</pre>
Line 1,521 ⟶ 1,568:
Here is a one-line solution.
A custom order relation can be defined for the OrderedQ[] function.
<langsyntaxhighlight Mathematicalang="mathematica">PermutationSort[x_List] := NestWhile[RandomSample, x, Not[OrderedQ[#]] &]</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
 
<langsyntaxhighlight MATLABlang="matlab">function list = permutationSort(list)
 
permutations = perms(1:numel(list)); %Generate all permutations of the item indicies
Line 1,537 ⟶ 1,584:
end
 
end</langsyntaxhighlight>
 
Sample Usage:
<langsyntaxhighlight MATLABlang="matlab">>> permutationSort([4 3 1 5 6 2])
 
ans =
 
1 2 3 4 5 6</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<langsyntaxhighlight MAXScriptlang="maxscript">fn inOrder arr =
(
if arr.count < 2 then return true
Line 1,575 ⟶ 1,622:
)
)
)</langsyntaxhighlight>
Output:
<syntaxhighlight lang="maxscript">
<lang MAXScript>
a = for i in 1 to 9 collect random 1 20
#(10, 20, 17, 15, 17, 15, 3, 11, 15)
permutations a
#(3, 10, 11, 15, 15, 15, 17, 17, 20)
</syntaxhighlight>
</lang>
Warning: This algorithm is very inefficient and Max will crash very quickly with bigger arrays.
 
=={{header|NetRexx}}==
Uses the permutation iterator '''<tt>RPermutationIterator</tt>''' at [[Permutations#NetRexx|Permutations]] to generate the permutations.
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,671 ⟶ 1,718:
method isFalse() public static returns boolean
return (1 == 0)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,692 ⟶ 1,739:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">iterator permutations[T](ys: openarray[T]): seq[T] =
var
d = 1
Line 1,729 ⟶ 1,776:
 
var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]
echo a.permSort</langsyntaxhighlight>
{{out}}
<pre>@[-31, 0, 2, 2, 4, 65, 83, 99, 782]</pre>
Line 1,735 ⟶ 1,782:
=={{header|OCaml}}==
Like the Haskell version, except not evaluated lazily. So it always computes all the permutations, before searching through them for a sorted one; which is more expensive than necessary; unlike the Haskell version, which stops generating at the first sorted permutation.
<langsyntaxhighlight lang="ocaml">let rec sorted = function
| e1 :: e2 :: r -> e1 <= e2 && sorted (e2 :: r)
| _ -> true
Line 1,746 ⟶ 1,793:
xs [[]]
 
let permutation_sort l = List.find sorted (permute l)</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">permutationSort(v)={
my(u);
for(k=1,(#v)!,
Line 1,758 ⟶ 1,805:
return(u)
)
};</langsyntaxhighlight>
 
=={{header|Perl}}==
Pass a list in by reference, and sort in situ.
<langsyntaxhighlight lang="perl">sub psort {
my ($x, $d) = @_;
 
Line 1,780 ⟶ 1,827:
print "Before:\t@a\n";
psort(\@a);
print "After:\t@a\n"</langsyntaxhighlight>
 
{{out}}
Line 1,787 ⟶ 1,834:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 1,806 ⟶ 1,853:
<span style="color: #0000FF;">?</span><span style="color: #000000;">permutationSort</span><span style="color: #0000FF;">({</span><span style="color: #008000;">"dog"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">15.545</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"cat"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"pile"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"abcde"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},</span><span style="color: #008000;">"cat"</span><span style="color: #0000FF;">})</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,813 ⟶ 1,860:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">function inOrder($arr){
for($i=0;$i<count($arr);$i++){
if(isset($arr[$i+1])){
Line 1,845 ⟶ 1,892:
$arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4);
$arr = permute($arr);
echo implode(',',$arr);</langsyntaxhighlight>
<pre>1,2,3,4,5,6,7,8,9,10</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de permutationSort (Lst)
(let L Lst
(recur (L) # Permute
Line 1,857 ⟶ 1,904:
(rot L)
NIL )
(apply <= Lst) ) ) ) )</langsyntaxhighlight>
{{out}}
<pre>: (permutationSort (make (do 9 (link (rand 1 999)))))
Line 1,869 ⟶ 1,916:
 
=={{header|PowerShell}}==
<langsyntaxhighlight PowerShelllang="powershell">Function PermutationSort( [Object[]] $indata, $index = 0, $k = 0 )
{
$data = $indata.Clone()
Line 1,908 ⟶ 1,955:
}
}
$l = 8; PermutationSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( 0, $l - 1 ) } )</langsyntaxhighlight>
 
=={{header|Prolog}}==
<langsyntaxhighlight lang="prolog">permutation_sort(L,S) :- permutation(L,S), sorted(S).
 
sorted([]).
Line 1,918 ⟶ 1,965:
 
permutation([],[]).
permutation([X|XS],YS) :- permutation(XS,ZS), select(X,YS,ZS).</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Macro reverse(firstIndex, lastIndex)
first = firstIndex
last = lastIndex
Line 1,978 ⟶ 2,025:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
<pre>8, 3, 10, 6, 1, 9, 7, -4, 5, 3
Line 1,985 ⟶ 2,032:
=={{header|Python}}==
{{works with|Python|2.6}}
<langsyntaxhighlight lang="python">from itertools import permutations
 
in_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1]))
perm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next()</langsyntaxhighlight>
 
<br/>
Line 1,994 ⟶ 2,041:
 
{{works with|Python|3.7}}
<langsyntaxhighlight lang="python">from itertools import permutations
from more_itertools import windowed
 
Line 2,009 ⟶ 2,056:
if is_sorted(permutation)
)
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ 1 swap times [ i 1+ * ] ] is ! ( n --> n )
 
[ [] unrot 1 - times
Line 2,027 ⟶ 2,074:
[ over size
factoradic inversion ] is nperm ( [ n --> [ )
 
[ true swap
behead swap
Line 2,040 ⟶ 2,088:
unrot 2drop ] is sort ( [ --> [ )
 
$ "beings" sort echo$</langsyntaxhighlight>
 
{{out}}
Line 2,050 ⟶ 2,098:
{{libheader|e1071}}
Warning: This function keeps all the possible permutations in memory at once, which becomes silly when x has 10 or more elements.
<langsyntaxhighlight lang="rsplus">permutationsort <- function(x)
{
if(!require(e1071) stop("the package e1071 is required")
Line 2,064 ⟶ 2,112:
x
}
permutationsort(c(1, 10, 9, 7, 3, 0))</langsyntaxhighlight>
 
===RcppAlgos===
{{libheader|RcppAlgos}}
RcppAlgos lets us do this at the speed of C++ and with some very short code. The while loop with no body strikes me as poor taste, but I know of no better way.
<langsyntaxhighlight lang="rsplus">library(RcppAlgos)
permuSort <- function(list)
{
Line 2,078 ⟶ 2,126:
test <- sample(10)
print(test)
permuSort(test)</langsyntaxhighlight>
{{out}}
<pre>#Output
Line 2,088 ⟶ 2,136:
 
An alternative solution would be to replace the while loop with the following:
<langsyntaxhighlight lang="rsplus">repeat
{
if(!is.unsorted(iter$nextIter())) break
}</langsyntaxhighlight>
This seems more explicit than the empty while loop, but also more complex.
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
(define (sort l)
(for/first ([p (in-permutations l)] #:when (apply <= p)) p))
(sort '(6 1 5 2 4 3)) ; => '(1 2 3 4 5 6)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line># Lexicographic permuter from "Permutations" task.
sub next_perm ( @a ) {
my $j = @a.end - 1;
Line 2,138 ⟶ 2,186:
say 'Input = ' ~ @data;
say 'Output = ' ~ @data.&permutation_sort;
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,145 ⟶ 2,193:
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program sorts and displays an array using the permutation-sort method. */
call gen /*generate the array elements. */
call show 'before sort' /*show the before array elements. */
Line 2,185 ⟶ 2,233:
do ?=1 until isOrd($); $= /*find permutation.*/
do m=1 for #; _= word(#.?, m); $= $ @._; end /*m*/ /*build the $ list.*/
end /*?*/; return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default (internal) inputs:}}
<pre>
Line 2,206 ⟶ 2,254:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Sorting algorithms/Permutation sort
 
Line 2,242 ⟶ 2,290:
ok
return a
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,251 ⟶ 2,299:
{{works with|Ruby|1.8.7+}}
The Array class has a permutation method that, with no arguments, returns an enumerable object.
<langsyntaxhighlight lang="ruby">class Array
def permutationsort
permutation.each{|perm| return perm if perm.sorted?}
Line 2,259 ⟶ 2,307:
each_cons(2).all? {|a, b| a <= b}
end
end</langsyntaxhighlight>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define (insertions e list)
(if (null? list)
(cons (cons e list) list)
Line 2,286 ⟶ 2,334:
(if (sorted? (car permutations))
(car permutations)
(loop (cdr permutations)))))</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func psort(x, d=x.end) {
 
if (d.is_zero) {
Line 2,311 ⟶ 2,359:
say "Before:\t#{a}";
psort(a);
say "After:\t#{a}";</langsyntaxhighlight>
{{out}}
<pre>
Line 2,321 ⟶ 2,369:
{{tcllib|struct::list}}
The <code>firstperm</code> procedure actually returns the lexicographically first permutation of the input list. However, to meet the letter of the problem, let's loop:
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
package require struct::list
 
Line 2,331 ⟶ 2,379:
}
return $list
}</langsyntaxhighlight>
 
=={{header|Ursala}}==
Standard library functions to generate permutations and test for ordering by a
given predicate are used.
<langsyntaxhighlight Ursalalang="ursala">#import std
 
permsort "p" = ~&ihB+ ordered"p"*~+ permutations
Line 2,342 ⟶ 2,390:
#cast %sL
 
example = permsort(lleq) <'pmf','oao','ejw','hhp','oqh','ock','dwj'></langsyntaxhighlight>
 
{{out}}
Line 2,350 ⟶ 2,398:
{{trans|Go}}
{{libheader|Wren-sort}}
<langsyntaxhighlight ecmascriptlang="wren">import "./sort" for Sort
 
var a = [170, 45, 75, -90, -802, 24, 2, 66]
Line 2,362 ⟶ 2,410:
a[i] = a[last]
a[last] = t
System.write("") // guard against VM recursion bug
if (recurse.call(last - 1)) return true
t = a[i]
Line 2,374 ⟶ 2,421:
var count = a.count
if (count > 1 && !recurse.call(count-1)) Fiber.abort("Sorted permutation not found!")
System.print("Sorted : %(a)")</langsyntaxhighlight>
 
{{out}}
Line 2,384 ⟶ 2,431:
=={{header|zkl}}==
Performance is horrid
<langsyntaxhighlight lang="zkl">rns:=T(4, 65, 2, 31, 0, 99, 2, 83, 782, 1);
fcn psort(list){ len:=list.len(); cnt:=Ref(0);
foreach ns in (Utils.Helpers.permuteW(list)){ // lasy permutations
Line 2,391 ⟶ 2,438:
if(cnt.value==len) return(ns);
}
}(rns).println();</langsyntaxhighlight>
{{out}}
<pre>L(0,1,2,2,4,31,65,83,99,782)</pre>
9,476

edits