Sorting algorithms/Permutation sort: Difference between revisions
Content added Content deleted
m (Unicon/Icon consistency) |
No edit summary |
||
Line 429: | Line 429: | ||
(A.~ps) list |
(A.~ps) list |
||
0 1 2 3 4 5 6 7 8 9</lang> |
0 1 2 3 4 5 6 7 8 9</lang> |
||
=={{header|PHP}}== |
|||
<lang php>function inOrder($arr){ |
|||
for($i=0;$i<count($arr);$i++){ |
|||
if(isset($arr[$i+1])){ |
|||
if($arr[$i] > $arr[$i+1]){ |
|||
return false; |
|||
} |
|||
} |
|||
} |
|||
return true; |
|||
} |
|||
function permute($items, $perms = array( )) { |
|||
if (empty($items)) { |
|||
if(inOrder($perms)){ |
|||
return $perms; |
|||
} |
|||
} else { |
|||
for ($i = count($items) - 1; $i >= 0; --$i) { |
|||
$newitems = $items; |
|||
$newperms = $perms; |
|||
list($foo) = array_splice($newitems, $i, 1); |
|||
array_unshift($newperms, $foo); |
|||
$res = permute($newitems, $newperms); |
|||
if($res){ |
|||
return $res; |
|||
} |
|||
} |
|||
} |
|||
} |
|||
$arr = array( 8, 3, 10, 6, 1, 9, 7, 2, 5, 4); |
|||
$arr = permute($arr); |
|||
echo implode(',',$arr);</lang> |
|||
<pre>1,2,3,4,5,6,7,8,9,10</pre> |
|||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
<lang prolog>permutation_sort(L,S) :- permutation(L,S), sorted(S). |
<lang prolog>permutation_sort(L,S) :- permutation(L,S), sorted(S). |