Sorting algorithms/Permutation sort: Difference between revisions

m
(Added Wren)
m (→‎{{header|Wren}}: Minor tidy)
 
(15 intermediate revisions by 10 users not shown)
Line 13:
'''done'''
<br><br>
=={{header|11l}}==
<syntaxhighlight lang="11l">F is_sorted(arr)
L(i) 1..arr.len-1
I arr[i-1] > arr[i]
R 0B
R 1B
 
F permutation_sort(&arr)
L !is_sorted(arr)
arr.next_permutation()
 
V arr = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]
permutation_sort(&arr)
print(arr)</syntaxhighlight>
 
{{out}}
<pre>
[0, 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">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program permutationSort64.s */
Line 259 ⟶ 279:
.include "../includeARM64.inc"
 
</syntaxhighlight>
</lang>
<pre>
Value : -5
Line 275 ⟶ 295:
sorted in +3467024 permutations
</pre>
 
=={{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 306 ⟶ 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 495 ⟶ 516:
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">sorted?: function [arr][
previous: first arr
 
loop slice arr 1 (size arr)-1 'item [
if not? item > previous -> return false
previous: item
]
return true
]
 
permutationSort: function [items][
loop permutate items 'perm [
if sorted? perm -> return perm
]
]
 
print permutationSort [3 1 2 8 5 7 9 4 6]</syntaxhighlight>
 
{{out}}
 
<pre>1 2 3 4 5 6 7 8 9</pre>
 
=={{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 540 ⟶ 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 587 ⟶ 633:
IF d(I%) < d(I%-1) THEN = FALSE
NEXT
= TRUE</langsyntaxhighlight>
{{out}}
<pre>
Line 595 ⟶ 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 640 ⟶ 686:
printf("%s\n", strs[i]);
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight Clang="c sharp|Cc#">
public static class PermutationSorter
{
Line 684 ⟶ 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 698 ⟶ 744:
// -- this block intentionally left empty --
}
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
 
<langsyntaxhighlight lang="lisp">
(use '[clojure.contrib.combinatorics :only (permutations)])
 
Line 709 ⟶ 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 772 ⟶ 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 794 ⟶ 840:
DONE!
sorted copy: [ 'a', 'b', 'c', 'd' ]
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
Line 802 ⟶ 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 835 ⟶ 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 846 ⟶ 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 866 ⟶ 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 883 ⟶ 929:
data.permutationSort;
data.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</pre>
Line 890 ⟶ 936:
===Alternative Version===
{{trans|C++}}
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm;
 
void permutationSort(T)(T[] items) pure nothrow @safe @nogc {
Line 900 ⟶ 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 907 ⟶ 953:
{{trans|C++}}
 
<langsyntaxhighlight lang="e">def swap(container, ixA, ixB) {
def temp := container[ixA]
container[ixA] := container[ixB]
Line 946 ⟶ 992:
def permutationSort(flexList) {
while (nextPermutation(flexList)) {}
}</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
;; This efficient sort method uses the list library for permutations
 
Line 967 ⟶ 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 987 ⟶ 1,033:
 
IO.inspect list = for _ <- 1..9, do: :rand.uniform(20)
IO.inspect Sort.permutation_sort(list)</langsyntaxhighlight>
 
{{out}}
Line 993 ⟶ 1,039:
[18, 2, 19, 10, 17, 10, 14, 8, 3]
[2, 3, 8, 10, 10, 14, 17, 18, 19]
</pre>
 
=={{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,003 ⟶ 1,096:
{ 10 2 6 8 1 4 3 } permutation-sort .
"apple" permutation-sort print</langsyntaxhighlight>
{{out}}
<pre>
Line 1,011 ⟶ 1,104:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 07-04-2017
' compile with: fbc -s console
 
Line 1,069 ⟶ 1,162:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>unsorted array
Line 1,081 ⟶ 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,119 ⟶ 1,212:
}
return false
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Line 1,125 ⟶ 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,146 ⟶ 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,156 ⟶ 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,170 ⟶ 1,263:
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">import Control.Monad
 
permutationSort l = head [p | p <- permute l, sorted p]
Line 1,181 ⟶ 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,212 ⟶ 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,230 ⟶ 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,284 ⟶ 1,377:
arr[j]=temp;
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,295 ⟶ 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,302 ⟶ 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,315 ⟶ 1,408:
else . as $in
| 1 | until( . == $length or $in[.-1] > $in[.] ; .+1) == $length
end;</langsyntaxhighlight>
 
'''Permutation-sort''':
Line 1,324 ⟶ 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,336 ⟶ 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,358 ⟶ 1,451:
 
x = randn(10)
@show x permsort(x)</langsyntaxhighlight>
 
{{out}}
Line 1,365 ⟶ 1,458:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun <T : Comparable<T>> isSorted(list: List<T>): Boolean {
Line 1,413 ⟶ 1,506:
val output2 = permutationSort(input2)
println("After sorting : $output2")
}</langsyntaxhighlight>
 
{{out}}
Line 1,425 ⟶ 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,454 ⟶ 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,468 ⟶ 1,561:
break:
end if:
end do:</langsyntaxhighlight>
{{Out|Output}}
<pre>[-1,0,0,17,72]</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Here is a one-line solution.
A custom order relation can be defined for the OrderedQ[] function.
<syntaxhighlight lang="mathematica">PermutationSort[x_List] := NestWhile[RandomSample, x, Not[OrderedQ[#]] &]</syntaxhighlight>
 
<lang Mathematica>PermutationSort[x_List] := NestWhile[RandomSample, x, Not[OrderedQ[#]] &]</lang>
 
=={{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,492 ⟶ 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,530 ⟶ 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,626 ⟶ 1,718:
method isFalse() public static returns boolean
return (1 == 0)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,647 ⟶ 1,739:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">iterator permutations[T](ys: openarray[T]): seq[T] =
var
d = 1
Line 1,684 ⟶ 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,690 ⟶ 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,701 ⟶ 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,713 ⟶ 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,735 ⟶ 1,827:
print "Before:\t@a\n";
psort(\@a);
print "After:\t@a\n"</langsyntaxhighlight>
 
{{out}}
Line 1,742 ⟶ 1,834:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function inOrder(sequence s)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
for i=2 to length(s) do
if s[i]<s[i-1] then return 0 end if
<span style="color: #008080;">function</span> <span style="color: #000000;">inOrder</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</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;">do</span>
return 1
<span style="color: #008080;">if</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]<</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #004600;">false</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
 
<span style="color: #008080;">return</span> <span style="color: #004600;">true</span>
function permutationSort(sequence s)
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
for n=1 to factorial(length(s)) do
sequence perm = permute(n,s)
<span style="color: #008080;">function</span> <span style="color: #000000;">permutationSort</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
if inOrder(perm) then return perm end if
<span style="color: #008080;">for</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">factorial</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;">do</span>
end for
<span style="color: #004080;">sequence</span> <span style="color: #000000;">perm</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">permute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
?9/0 -- should never happen
<span style="color: #008080;">if</span> <span style="color: #000000;">inOrder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">perm</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #000000;">perm</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
 
<span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #000080;font-style:italic;">-- should never happen</span>
?permutationSort({"dog",0,15.545,{"cat","pile","abcde",1},"cat"})</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<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>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,764 ⟶ 1,860:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">function inOrder($arr){
for($i=0;$i<count($arr);$i++){
if(isset($arr[$i+1])){
Line 1,796 ⟶ 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,808 ⟶ 1,904:
(rot L)
NIL )
(apply <= Lst) ) ) ) )</langsyntaxhighlight>
{{out}}
<pre>: (permutationSort (make (do 9 (link (rand 1 999)))))
Line 1,820 ⟶ 1,916:
 
=={{header|PowerShell}}==
<langsyntaxhighlight PowerShelllang="powershell">Function PermutationSort( [Object[]] $indata, $index = 0, $k = 0 )
{
$data = $indata.Clone()
Line 1,859 ⟶ 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,869 ⟶ 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,929 ⟶ 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,936 ⟶ 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,945 ⟶ 2,041:
 
{{works with|Python|3.7}}
<langsyntaxhighlight lang="python">from itertools import permutations
from more_itertools import windowed
 
Line 1,960 ⟶ 2,056:
if is_sorted(permutation)
)
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ 1 swap times [ i 1+ * ] ] is ! ( n --> n )
 
[ [] unrot 1 - times
[ i 1+ ! /mod
dip join ] drop ] is factoradic ( n n --> [ )
 
[ [] unrot witheach
[ pluck
rot swap nested join
swap ]
join ] is inversion ( [ [ --> [ )
 
[ over size
factoradic inversion ] is nperm ( [ n --> [ )
 
[ true swap
behead swap
witheach
[ tuck > if
[ dip not conclude ] ]
drop ] is sorted ( [ --> b )
 
[ 0
[ 2dup nperm
dup sorted not while
drop 1+ again ]
unrot 2drop ] is sort ( [ --> [ )
 
$ "beings" sort echo$</syntaxhighlight>
 
{{out}}
 
<pre>begins</pre>
 
=={{header|R}}==
===e1071===
{{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 rlang="rsplus">permutationsort <- function(x)
{
if(!require(e1071) stop("the package e1071 is required")
Line 1,979 ⟶ 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.
<syntaxhighlight lang="rsplus">library(RcppAlgos)
permuSort <- function(list)
{
iter <- permuteIter(list)
while(is.unsorted(iter$nextIter())){}#iter$nextIter advances iter to the next iteration and returns it.
iter$currIter()
}
test <- sample(10)
print(test)
permuSort(test)</syntaxhighlight>
{{out}}
<pre>#Output
> test <- sample(10)
> print(test)
[1] 8 10 6 2 9 4 7 5 3 1
> permuSort(test)
[1] 1 2 3 4 5 6 7 8 9 10</pre>
 
An alternative solution would be to replace the while loop with the following:
<syntaxhighlight lang="rsplus">repeat
{
if(!is.unsorted(iter$nextIter())) break
}</syntaxhighlight>
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,025 ⟶ 2,186:
say 'Input = ' ~ @data;
say 'Output = ' ~ @data.&permutation_sort;
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,032 ⟶ 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. */
say copies('░', 75) say copies('░', 75) /*show separator line between displays.*/
call pSort L L /*invoke the permutation sort. */
call show ' after sort' /*show the after array elements. */
say; say 'Permutation sort took ' ? " permutations to find the sorted list."
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
.pAdd: #=#+1; do j=1 for N; #.#=#.# !.j; end; return /*add a permutation.*/
show: do j=1 for L; say @e right(j, wL) arg(1)":" translate(@.j, , '_'); end; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
gen: @.=; @.1 = '---Four_horsemen_of_the_Apocalypse---'
@.2 = '====================================='
@.3 = 'Famine───black_horse'
@.4 = 'Death───pale_horse'
@.5 = 'Pestilence_[Slaughter]───red_horse'
@.6 = 'Conquest_[War]───white_horse'
@e= right('element', 15) /*literal used for the display.*/
do L=1 while @.L\==''; @@.L=@.L; end; L= L-1; wL=length(L); return
/*──────────────────────────────────────────────────────────────────────────────────────*/
isOrd: parse arg q /*see if Q list is in order. */
_= word(q, 1); do j=2 to words(q); x= word(q, j); if x<_ then return 0; _= x
end /*j*/ /* [↑] Out of order? ¬sorted*/
do k=1 for #; _= word(#.?, k); @.k= @@._; end /*k*/; return 1 /*in order.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
.pNextpNxt: procedure expose !.; parse arg n,i; nm= n - 1
do k=nm by -1 for nm; kp= k + 1
if !.k<!.kp then do; i= k; leave; end
end /*k*/ /* [↓] swap two array elements*/
do j=i+1 while j<n; parse value !.j !.n with !.n !.j; n= n-1; end /*j*/
if i==0 then return 0 /*0: indicates no more perms. */
do j=i+1 while !.j<!.i; end /*j*/ /*search perm for a lower value*/
parse value !.j !.i with !.i !.j; return 1 /*swap two values in !. array.*/
return 1
/*──────────────────────────────────────────────────────────────────────────────────────*/
pSort: parse arg n,#.; #= 0 /*generate L items (!) permutations.*/
do f=1 for n; !.f= f; end /*f*/; call .pAdd
call .pAdd; do while .pNextpNxt(n, 0); call .pAdd; end /*while*/
do ?=1 until isOrd($); $= /*find permpermutation.*/
do m=1 for #; _= word(#.?, m); $= $ @._; end /*m*/ /*build the $ list.*/
end /*?*/; end return</*?*/syntaxhighlight>
return</lang>
{{out|output|text=&nbsp; when using the default (internal) inputs:}}
<pre>
Line 2,095 ⟶ 2,254:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Sorting algorithms/Permutation sort
 
Line 2,131 ⟶ 2,290:
ok
return a
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,140 ⟶ 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,148 ⟶ 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,175 ⟶ 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,200 ⟶ 2,359:
say "Before:\t#{a}";
psort(a);
say "After:\t#{a}";</langsyntaxhighlight>
{{out}}
<pre>
Line 2,210 ⟶ 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,220 ⟶ 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,231 ⟶ 2,390:
#cast %sL
 
example = permsort(lleq) <'pmf','oao','ejw','hhp','oqh','ock','dwj'></langsyntaxhighlight>
 
{{out}}
Line 2,239 ⟶ 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,251 ⟶ 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,263 ⟶ 2,421:
var count = a.count
if (count > 1 && !recurse.call(count-1)) Fiber.abort("Sorted permutation not found!")
System.print("Sorted : %(a)")</syntaxhighlight>
 
System.print("Unsorted: %(a)")
var count = a.count
if (count > 1 && !recurse.call(count-1)) Fiber.abort("Sorted permutation not found!")
System.print("Sorted : %(a)")</lang>
 
{{out}}
Line 2,278 ⟶ 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,285 ⟶ 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