Sorting algorithms/Cycle sort: Difference between revisions

m
→‎{{header|Wren}}: 'as' is now a keyword.
(Rename Perl 6 -> Raku, alphabetize, minor clean-up)
m (→‎{{header|Wren}}: 'as' is now a keyword.)
 
(24 intermediate revisions by 15 users not shown)
Line 1:
{{draft task|Sorting Algorithms}}<!--Add this back when it gets promoted, also add a link to this page to the n^2 sorts in the template{{Sorting Algorithm}}-->
{{Sorting Algorithm}}
{{wikipedia|Cycle_sort}}
[[Category:Sorting]]
 
{{Wikipedia|Cycle_sort}}
<!-- also known as a cyclic sort !-->
 
<br>
Line 16 ⟶ 20:
* [http://www.youtube.com/watch?v=ZSJGf5Ngw18 Youtube] Visualization and audibilization of Cycle Sort algorithm.
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F cycleSort(&vector)
V writes = 0
 
L(=item) vector
V cycleStart = L.index
V pos = cycleStart
L(item2) vector[cycleStart+1..]
I item2 < item
pos++
 
I pos == cycleStart
L.continue
 
L item == vector[pos]
pos++
swap(&vector[pos], &item)
writes++
 
L pos != cycleStart
pos = cycleStart
L(item2) vector[cycleStart+1..]
I item2 < item
pos++
 
L item == vector[pos]
pos++
swap(&vector[pos], &item)
writes++
 
R writes
 
V x = [Float(0), 1, 2, 2, 2, 2, 1, 9, 3.5, 5, 8, 4, 7, 0, 6]
V xcopy = copy(x)
V writes = cycleSort(&xcopy)
I xcopy != sorted(x)
print(‘Wrong order!’)
E
print("#.\nIs correctly sorted using cycleSort to".format(x))
print("#.\nUsing #. writes.".format(xcopy, writes))</syntaxhighlight>
 
{{out}}
<pre>
[0, 1, 2, 2, 2, 2, 1, 9, 3.5, 5, 8, 4, 7, 0, 6]
Is correctly sorted using cycleSort to
[0, 0, 1, 1, 2, 2, 2, 2, 3.5, 4, 5, 6, 7, 8, 9]
Using 10 writes.
</pre>
 
=={{header|360 Assembly}}==
{{trans|NetRexx}}
The program uses ASM structured macros and two ASSIST macros to keep the code as short as possible.
<langsyntaxhighlight lang="360asm">* Cycle sort 26/06/2016
CYCLESRT CSECT
USING CYCLESRT,R13 base register
Line 130 ⟶ 185:
RT EQU 9 temp
RM EQU 10 item
END CYCLESRT</langsyntaxhighlight>
{{out}}
<pre>
-31 0 1 2 2 4 45 58 65 69 74 82 82 83 88 89 99 104 112 782
</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 CycleSort(INT ARRAY a INT size)
BYTE start,i,pos
INT item,tmp
 
FOR start=0 TO size-2
DO
item=a(start)
pos=start
FOR i=start+1 TO size-1
DO
IF a(i)<item THEN
pos==+1
FI
OD
IF pos#start THEN
tmp=a(pos) a(pos)=item item=tmp
WHILE pos#start
DO
pos=start
FOR i=start+1 TO size-1
DO
IF a(i)<item THEN
pos==+1
FI
OD
WHILE item=a(pos)
DO
pos==+1
OD
tmp=a(pos) a(pos)=item item=tmp
OD
FI
OD
RETURN
 
PROC Test(INT ARRAY a INT size)
PrintE("Array before sort:")
PrintArray(a,size)
CycleSort(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/Cycle_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|ALGOL 68}}==
{{Trans|Action!}}
<syntaxhighlight lang="algol68">
BEGIN # cycle sort - translated from the Action! sample #
 
# prints the elements of a #
OP SHOW = ( REF[]INT a )VOID:
BEGIN
print( ( "[" ) );
FOR i FROM LWB a TO UPB a DO
print( ( " ", whole( a[ i ], 0 ) ) )
OD;
print( " ]" )
END # SHOW # ;
 
# swaps a and b #
PRIO =:= = 1;
OP =:= = ( REF INT a, b )VOID: BEGIN INT t := a; a := b; b := t END;
 
# cycle sorts a #
PROC cycle sort = ( REF[]INT a )VOID:
FOR start FROM LWB a TO UPB a - 1 DO
INT item := a[ start ];
INT pos := start;
FOR i FROM start + 1 TO UPB a DO
IF a[ i ] < item THEN
pos +:= 1
FI
OD;
IF pos /= start THEN
item =:= a[ pos ];
WHILE pos /= start DO
pos := start;
FOR i FROM start + 1 TO UPB a DO
IF a[ i ] < item THEN
pos +:= 1
FI
OD;
WHILE item = a[ pos ] DO
pos +:= 1
OD;
a[ pos ] =:= item
OD
FI
OD # cycle sort # ;
PROC test = ( REF[]INT a )VOID:
BEGIN
print( ( "Array before sort: " ) ); SHOW a; print( ( newline ) );
cycle sort( a );
print( ( "Array after sort: " ) ); SHOW a; print( ( newline ) );
END # test # ;
 
BEGIN # tests #
[ 10 ]INT a := []INT( 1, 4, -1, 0, 3, 7, 4, 8, 20, -6 );
[ 21 ]INT b := []INT( 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0
, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10
);
[ 8 ]INT c := []INT( 101, 102, 103, 104, 105, 106, 107, 108 );
[ 12 ]INT d := []INT( 1 ,-1, 1,-1, 1, -1, 1, -1, 1, -1, 1, -1 );
test( a );
test( b );
test( c );
test( d )
END
END
</syntaxhighlight>
{{out}}
<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|ALGOL W}}==
{{Trans|Lua}}
<syntaxhighlight lang="algolw">
begin % cycle sort %
 
% cycle sorts a, the bounds of a must be specified in lb and ub %
integer procedure cycleSort ( integer array a ( * ); integer value lb, ub ) ;
begin
% swaps a and b %
procedure swap ( integer value result a, b ) ;
begin integer t;
t := a; a := b; b := t;
swaps := swaps + 1
end swap ;
integer swaps, cycleStart, cycleEnd, val, pos;
swaps := 0;
cycleStart := lb - 1;
while cycleStart < ub do begin
val := a( cycleStart + 1 );
% count the number of values that are smaller than val since cycleStart %
pos := cycleStart;
for i := cycleStart + 1 until ub - 1 do begin
if a( i + 1 ) < val then pos := pos + 1
end for_i ;
if pos not = cycleStart then begin % there aren't any %
while val = a( pos + 1 ) do pos := pos + 1;
swap( a( pos + 1 ), val ); % put val in final position %
% repeat as long as we can find values to swap %
% otherwise start new cycle %
while pos not = cycleStart do begin
pos := cycleStart;
for i := cycleStart + 1 until ub- 1 do begin
if a( i + 1 ) < val then pos := pos + 1;
end for_i ;
while val = a( pos + 1 ) do pos := pos + 1;
swap( a( pos + 1 ), val );
end while_pos_ne_cycleStart
end if_pos_ne_cycleStart ;
cycleStart := cycleStart + 1
end while_cycleStart_lt_ub ;
swaps
end cycleSort ;
 
% prints the elements of a from lb to ub %
procedure writeonArray( integer array a ( * ); integer value lb, ub ) ;
begin
writeon( "(" );
for i := lb until ub do writeon( i_w := 1, s_w := 0, " ", a( i ) );
writeon( " )" )
end writeonArray ;
 
begin % tests %
integer array arr ( 1 :: 16 );
integer aPos, swaps;
aPos := 1;
for v := 5, 0, 1, 2, 2, 3, 5, 1, 1, 0, 5, 6, 9, 8, 0, 1 do begin
arr( aPos ) := v;
aPos := aPos + 1
end for_v ;
writeonArray( arr, 1, 16 );
writeon( " -> " );
swaps := cycleSort( arr, 1, 16 );
writeonArray( arr, 1, 16 );
write( i_w := 1, s_w := 0, "swaps: ", swaps )
end
end.
</syntaxhighlight>
{{out}}
<pre>
( 5 0 1 2 2 3 5 1 1 0 5 6 9 8 0 1 ) -> ( 0 0 0 1 1 1 1 2 2 3 5 5 5 6 8 9 )
swaps: 14
</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">cycleSort: function [items][
a: new items
position: 0
loop 0..dec dec size a 'cycleStart [
item: a\[cycleStart]
position: cycleStart
loop (cycleStart+1)..dec size a 'i [
if (get a i) < item -> position: position + 1
]
if position = cycleStart -> continue
while [item = a\[position]] -> position: position + 1
 
tmp: a\[position]
a\[position]: item
item: tmp
 
while [position <> cycleStart][
position: cycleStart
loop (cycleStart+1)..dec size a 'i [
if a\[i] < item -> position: position + 1
]
while [item = a\[position]] -> position: position + 1
 
tmp: a\[position]
a\[position]: item
item: tmp
]
]
return a
]
 
print cycleSort [3 1 2 8 5 7 9 4 6]</syntaxhighlight>
 
{{out}}
 
<pre>1 2 3 4 5 6 7 8 9</pre>
 
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
 
// Sort an array in place and return the number of writes
let cyclesort(v, len) = valof
$( let writes, temp = 0, ?
 
// Loop through the array to find cycles to rotate
for start = 0 to len-1
$( let item = v!start
// Find where to put the item
let pos = start
for i = start+1 to len-1
if v!i < item then pos := pos + 1
// If the item is already there, this is not a cycle
if pos = start loop
// Otherwise, put the item there or right after any duplicates
while item = v!pos do pos := pos + 1
temp := v!pos
v!pos := item
item := temp
writes := writes + 1
// Rotate the rest of the cycle
until pos = start
$( // Find where to put the item
pos := start
for i = start+1 to len-1
if v!i < item then pos := pos + 1
// Put the item there or right after any duplicates
while item = v!pos do pos := pos + 1
temp := v!pos
v!pos := item
item := temp
writes := writes + 1
$)
$)
resultis writes
$)
 
let writevec(v, len) be
$( for i = 0 to len-1 do
writef("%N ", v!i)
wrch('*N')
$)
 
let start() be
$( let v = table 0,1,2,2,2,2,1,9,3,5,5,8,4,7,0,6
let l = 16
let w = ?
writes("Before: ") ; writevec(v, l)
w := cyclesort(v)
writes("After: ") ; writevec(v, l)
writef("Writes: %N*N", w)
$)</syntaxhighlight>
{{out}}
<pre>Before: 0 1 2 2 2 2 1 9 3 5 5 8 4 7 0 6
After: 0 0 1 1 2 2 2 2 3 4 5 5 6 7 8 9
Writes: 10</pre>
 
=={{header|C}}==
{{trans|NetRexx}}
<syntaxhighlight lang="c">
<lang C>
#include <stdio.h>
#include <stdlib.h>
Line 236 ⟶ 645:
return;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 246 ⟶ 655:
=={{header|C++}}==
Based on example code on Wikipedia
<syntaxhighlight lang="cpp">
<lang Cpp>
#include <time.h>
#include <iostream>
Line 312 ⟶ 721:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 323 ⟶ 732:
This version doesn't use Phobos algorithms beside 'swap'. Algorithms can be used to find where to put the item1 and elsewhere.
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm;
 
/// Sort an array in place and return the number of writes.
Line 377 ⟶ 786:
writefln("%s\nusing %d writes.", xs, nWrites);
}
}</langsyntaxhighlight>
{{out}}
<pre>[0, 1, 2, 2, 2, 2, 1, 9, 3.5, 5, 8, 4, 7, 0, 6]
Line 386 ⟶ 795:
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule Sort do
def cycleSort(list) do
tuple = List.to_tuple(list)
Line 428 ⟶ 837:
{b, writes} = Sort.cycleSort(a)
IO.puts "writes : #{writes}"
IO.inspect b</langsyntaxhighlight>
 
{{out}}
Line 439 ⟶ 848:
=={{header|FreeBASIC}}==
Uses algorithm in Wikipedia article:
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
' sort an array in place and return the number of writes
Line 507 ⟶ 916:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 523 ⟶ 932:
This implementation was translated from the example code on Wikipedia.
 
<langsyntaxhighlight lang="go">package main
 
import (
Line 585 ⟶ 994:
fmt.Printf("writes %d\n", cyclesort(ints))
fmt.Println(ints)
}</langsyntaxhighlight>
 
{{out}}
Line 595 ⟶ 1,004:
 
Note: output may be different due to the random numbers used.
 
=={{header|Groovy}}==
{{trans|Java}}
<syntaxhighlight lang="groovy">class CycleSort {
static void main(String[] args) {
int[] arr = [5, 0, 1, 2, 2, 3, 5, 1, 1, 0, 5, 6, 9, 8, 0, 1]
 
println(Arrays.toString(arr))
 
int writes = cycleSort(arr)
println(Arrays.toString(arr))
println("writes: " + writes)
}
 
static int cycleSort(int[] a) {
int writes = 0
 
for (int cycleStart = 0; cycleStart < a.length - 1; cycleStart++) {
int val = a[cycleStart]
 
// count the number of values that are smaller than val
// since cycleStart
int pos = cycleStart
for (int i = cycleStart + 1; i < a.length; i++) {
if (a[i] < val) {
pos++
}
}
 
// there aren't any
if (pos == cycleStart) {
continue
}
 
// skip duplicates
while (val == a[pos]) {
pos++
}
 
// put val into final position
int tmp = a[pos]
a[pos] = val
val = tmp
writes++
 
// repeat as long as we can find values to swap
// otherwise start new cycle
while (pos != cycleStart) {
pos = cycleStart
for (int i = cycleStart + 1; i < a.length; i++) {
if (a[i] < val) {
pos++
}
}
 
while (val == a[pos]) {
pos++
}
 
tmp = a[pos]
a[pos] = val
val = tmp
writes++
}
}
return writes
}
}</syntaxhighlight>
{{out}}
<pre>[5, 0, 1, 2, 2, 3, 5, 1, 1, 0, 5, 6, 9, 8, 0, 1]
[0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 5, 5, 5, 6, 8, 9]
writes: 14</pre>
 
=={{header|J}}==
Line 601 ⟶ 1,082:
It would be trivial do the writes one at a time, and to avoid updating values which are not changed:
 
<langsyntaxhighlight Jlang="j">noncyc=:3 :0
writes=. 0
for_item. /:~y do.
Line 611 ⟶ 1,092:
smoutput (":writes),' writes'
y
)</langsyntaxhighlight>
 
{{out|Example use}}
<langsyntaxhighlight Jlang="j"> noncyc 9 8 15 17 4 0 1 2 17 9 3 12 11 12 19 15 3 9 16 9
17 writes
0 1 2 3 3 4 8 9 9 9 9 11 12 12 15 15 16 17 17 19</langsyntaxhighlight>
 
Meanwhile, if we just wanted the "value at a time swapping" mechanism,
an idiomatic approach might look something like this:
 
<langsyntaxhighlight lang="j">cyc0=:3 :0
c=. (#~ 1 < #@>)C./:/: y
writes=. 0
Line 636 ⟶ 1,117:
smoutput (":writes),' writes'
y
)</langsyntaxhighlight>
 
{{out|Example use}}
<langsyntaxhighlight Jlang="j"> cyc0 9 8 15 17 4 0 1 2 17 9 3 12 11 12 19 15 3 9 16 9
18 writes
0 1 2 3 3 4 8 9 9 9 9 11 12 12 15 15 16 17 17 19</langsyntaxhighlight>
 
This gives us an extra write, because we're using a generic cycle abstraction.
Line 648 ⟶ 1,129:
We might model the wikipedia algorithm like this:
 
<langsyntaxhighlight Jlang="j">cyc1=:3 :0
writes=. 0
for_index. i.(#y)-1 do.
Line 672 ⟶ 1,153:
smoutput (":writes),' writes'
y
)</langsyntaxhighlight>
 
{{out|Example use}}
<langsyntaxhighlight Jlang="j"> cyc1 9 8 15 17 4 0 1 2 17 9 3 12 11 12 19 15 3 9 16 9
17 writes
0 1 2 3 3 4 8 9 9 9 9 11 12 12 15 15 16 17 17 19</langsyntaxhighlight>
 
Note that we've saved a write in this case, by following the wikipedia algorithm.
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.util.Arrays;
 
public class CycleSort {
Line 742 ⟶ 1,223:
return writes;
}
}</langsyntaxhighlight>
 
{{out}}
Line 748 ⟶ 1,229:
[0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 5, 5, 5, 6, 8, 9]
writes: 14</pre>
 
=={{header|jq}}==
{{trans|Wren}}
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
The following implementation is based on the [[#Wren|Wren]] entry except for the
use of `swap`, which exposes a bug in the Wren version (as of 2021.09.12) regarding `writes`.
<syntaxhighlight lang="jq">
# Output: {a: sortedInput, write: numberOfSwaps}
def cycleSort:
def swap(f;g): g as $t | g = f | f = $t | .writes += 1;
 
{ a: ., writes: 0, len: length }
| reduce range(0; .len - 1) as $cs (.;
.item = .a[$cs]
| .pos = $cs
| reduce range($cs+1; .len) as $i (.;
if .a[$i] < .item then .pos += 1 else . end )
| if .pos != $cs
then until (.item != .a[.pos]; .pos += 1)
| swap(.a[.pos]; .item)
| until (.pos == $cs;
.pos = $cs
| reduce range($cs+1; .len) as $i (.;
if .a[$i] < .item then .pos += 1 else . end)
| until (.item != .a[.pos]; .pos += 1)
| swap(.a[.pos]; .item) )
else .
end )
| {a, writes} ;</syntaxhighlight>
'''The Task'''
<syntaxhighlight lang="jq">[0, 1, 2, 2, 2, 2, 1, 9, 3.5, 5, 8, 4, 7, 0, 6],
[4, 65, 2, -31, 0, 99, 2, 83, 782, 1],
[7, 5, 2, 6, 1, 4, 2, 6, 3]
| "Before : \(.)",
(cycleSort
| "After : \(.a)",
"Writes : \(.writes)",
"")</syntaxhighlight>
{{out}}
<pre>
Before : [0,1,2,2,2,2,1,9,3.5,5,8,4,7,0,6]
After : [0,0,1,1,2,2,2,2,3.5,4,5,6,7,8,9]
Writes : 10
 
Before : [4,65,2,-31,0,99,2,83,782,1]
After : [-31,0,1,2,2,4,65,83,99,782]
Writes : 9
 
Before : [7,5,2,6,1,4,2,6,3]
After : [1,2,2,3,4,5,6,6,7]
Writes : 7
</pre>
 
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">function cyclesort!(v::Vector)
writes = 0
for (cyclestart, item) in enumerate(v)
Line 784 ⟶ 1,320:
 
v = rand(-10:10, 10)
println("# unordered: $v\n -> ordered: ", cyclesort!(v))</langsyntaxhighlight>
 
{{out}}
Line 792 ⟶ 1,328:
=={{header|Kotlin}}==
Translation of the algorithm in the Wikipedia article:
<langsyntaxhighlight lang="scala">// version 1.1.0
 
/** Sort an array in place and return the number of writes */
Line 850 ⟶ 1,386:
val array4 = "sphinx of black quartz judge my vow".replace(" ", "").toCharArray().distinct().toTypedArray()
printResults(array4)
}</langsyntaxhighlight>
 
{{out}}
Line 870 ⟶ 1,406:
[a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z]
</pre>
 
=={{header|Lua}}==
{{trans|Java}}
<syntaxhighlight lang="lua">function printa(a)
io.write("[")
for i,v in ipairs(a) do
if i > 1 then
io.write(", ")
end
io.write(v)
end
io.write("]")
end
 
function cycle_sort(a)
local writes = 0
 
local cycle_start = 0
while cycle_start < #a - 1 do
local val = a[cycle_start + 1]
 
-- count the number of values that are smaller than val since cycle_start
local pos = cycle_start
local i = cycle_start + 1
while i < #a do
if a[i + 1] < val then
pos = pos + 1
end
i = i + 1
end
 
-- there aren't any
if pos ~= cycle_start then
-- skip duplicates
while val == a[pos + 1] do
pos = pos + 1
end
 
-- put val in final position
a[pos + 1], val = val, a[pos + 1]
writes = writes + 1
 
-- repeat as long as we can find values to swap
-- otherwise start new cycle
while pos ~= cycle_start do
pos = cycle_start
local i = cycle_start + 1
while i < #a do
if a[i + 1] < val then
pos = pos + 1
end
i = i + 1
end
 
while val == a[pos + 1] do
pos = pos + 1
end
 
a[pos + 1], val = val, a[pos + 1]
writes = writes + 1
end
end
cycle_start = cycle_start + 1
end
 
return writes
end
 
arr = {5, 0, 1, 2, 2, 3, 5, 1, 1, 0, 5, 6, 9, 8, 0, 1}
 
printa(arr)
print()
 
writes = cycle_sort(arr)
printa(arr)
print()
print("writes: " .. writes)</syntaxhighlight>
{{out}}
<pre>[5, 0, 1, 2, 2, 3, 5, 1, 1, 0, 5, 6, 9, 8, 0, 1]
[0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 5, 5, 5, 6, 8, 9]
writes: 14</pre>
 
=={{header|NetRexx}}==
Direct translation of [[wp:Cycle sort|the Wikipedia entry]] example
<langsyntaxhighlight NetRexxlang="netrexx">/* Rexx */
options replace format comments java crossref symbols nobinary
 
Line 951 ⟶ 1,568:
end i_
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 975 ⟶ 1,592:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc cycleSort[T](a: var openArray[T]): int =
var position, writes: int = 0
var item: T
Line 1,031 ⟶ 1,648:
writes = array5.cycleSort()
echo "Sorted: ", $array5
echo "Total number of writes: ", writes</langsyntaxhighlight>
 
{{out}}
Line 1,056 ⟶ 1,673:
=={{header|Objeck}}==
{{trans|Java}}
<langsyntaxhighlight lang="objeck">class Test {
function : Main(args : String[]) ~ Nil {
arr := [5, 0, 1, 2, 2, 3, 5, 1, 1, 0, 5, 6, 9, 8, 0, 1];
Line 1,110 ⟶ 1,727:
return writes;
}
}</langsyntaxhighlight>
 
<pre>
Line 1,119 ⟶ 1,736:
 
=={{header|ooRexx}}==
<langsyntaxhighlight lang="oorexx">/*REXX program demonstrates a cycle sort on a list of numbers**********
* 13.06.2014 Walter Pachl
* Modified from Rexx Version 2
Line 1,183 ⟶ 1,800:
Say format(i,2) a.i
End
Return</langsyntaxhighlight>
{{out}}
<pre>
Line 1,205 ⟶ 1,822:
=={{header|Perl}}==
This is based on the Wikipedia pseudocode.
<langsyntaxhighlight lang="perl">use strict;
use warnings;
 
sub cycleSort :prototype(@) {
my ($array) = @_;
my $writes = 0;
Line 1,252 ⟶ 1,869:
print "There were ", cycleSort( \@test ), " writes\n";
print "After sorting: @test\n";
</syntaxhighlight>
</lang>
{{out}}
<pre>Before sorting: a t d b f g y l t p w c r r x i y j k i z q e v a f o q j u x k m h s u v z g m b o l e n h p n c s w d
Line 1,261 ⟶ 1,878:
{{trans|NetRexx}}
plus some factoring out of common code
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>sequence array
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
object item
integer pos, writes
 
procedure find_item(integer cycle_start)
-- Find where to put the item.
pos = cycle_start
for i=cycle_start+1 to length(array) do
if array[i] < item then
pos = pos + 1
end if
end for
end procedure
 
procedure put_item()
-- Put the item there or right after any duplicates.
while item == array[pos] do
pos = pos + 1
end while
{array[pos],item} = {item,array[pos]}
writes += 1
end procedure
 
-- Sort an array in place and return the number of writes.
procedure cycleSort()
writes = 0
-- Loop through the array to find cycles to rotate.
for cycle_start=1 to length(array)-1 do
item = array[cycle_start]
find_item(cycle_start)
-- If the item is already there, this is not a cycle.
if pos!=cycle_start then
put_item()
-- Rotate the rest of the cycle.
while pos!=cycle_start do
find_item(cycle_start)
put_item()
end while
end if
end for
end procedure
<span style="color: #004080;">sequence</span> <span style="color: #000000;">array</span>
constant samples = {{1, 9, 3, 5, 8, 4, 7, 0, 6, 2},
<span style="color: #004080;">object</span> <span style="color: #000000;">item</span>
{0, 1, 2, 2, 2, 2, 1, 9, 3.5, 5, 8, 4, 7, 0, 6},
<span style="color: #004080;">integer</span> <span style="color: #000000;">pos</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">writes</span>
{"Greygill Hole", "Ogof Draenen", "Ogof Ffynnon Ddu", "Malham Tarn Pot"},
{-3.14 ,3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3, 8, 4, 6, 2, 6, 4, 3, 3, 8, 3, 2, 7, 9, 5, 0, 2, 8, 8, 4},
<span style="color: #008080;">procedure</span> <span style="color: #000000;">find_item</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">cycle_start</span><span style="color: #0000FF;">)</span>
{5,0,1,2,2,3,5,1,1,0,5,6,9,8,0,1},
<span style="color: #000080;font-style:italic;">-- Find where to put the item.</span>
{1,1,1,1,1,1}}
<span style="color: #000000;">pos</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">cycle_start</span>
 
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">cycle_start</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">array</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
for i=1 to length(samples) do
<span style="color: #008080;">if</span> <span style="color: #000000;">array</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: #000000;">item</span> <span style="color: #008080;">then</span>
array = samples[i]
<span style="color: #000000;">pos</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">pos</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">1</span>
puts(1,"Input list ") ?array
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
cycleSort()
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
puts(1,"Sorted list ") ?array
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
printf(1,"Total number of writes: %d (out of %d)\n", {writes,length(array)})
end for</lang>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">put_item</span><span style="color: #0000FF;">()</span>
<span style="color: #000080;font-style:italic;">-- Put the item there or right after any duplicates.</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">item</span> <span style="color: #0000FF;">==</span> <span style="color: #000000;">array</span><span style="color: #0000FF;">[</span><span style="color: #000000;">pos</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">pos</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">pos</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">ap</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">array</span><span style="color: #0000FF;">[</span><span style="color: #000000;">pos</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">array</span><span style="color: #0000FF;">[</span><span style="color: #000000;">pos</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">item</span>
<span style="color: #000000;">item</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ap</span>
<span style="color: #000000;">writes</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000080;font-style:italic;">-- Sort an array in place and return the number of writes.</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">cycleSort</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">writes</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #000000;">array</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">array</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- Loop through the array to find cycles to rotate.</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">cycle_start</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">array</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">item</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">array</span><span style="color: #0000FF;">[</span><span style="color: #000000;">cycle_start</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">find_item</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cycle_start</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- If the item is already there, this is not a cycle.</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">pos</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">cycle_start</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">put_item</span><span style="color: #0000FF;">()</span>
<span style="color: #000080;font-style:italic;">-- Rotate the rest of the cycle.</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">pos</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">cycle_start</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">find_item</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cycle_start</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">put_item</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">samples</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">9</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">9</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3.5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">6</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #008000;">"Greygill Hole"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Ogof Draenen"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Ogof Ffynnon Ddu"</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"Malham Tarn Pot"</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{-</span><span style="color: #000000;">3.14</span> <span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">9</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">9</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">9</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">9</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">4</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9</span><span style="color: #0000FF;">,</span><span style="color: #000000;">8</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">}}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">samples</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">array</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">samples</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Input list "</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">array</span>
<span style="color: #000000;">cycleSort</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Sorted list "</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">array</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Total number of writes: %d (out of %d)\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">writes</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">array</span><span style="color: #0000FF;">)})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,342 ⟶ 1,966:
The Wikipedia algorithm pseudocode is very nearly Python. The main changes needed were to change the name array to vector to stop it obscuring a built-in name, and iterating over an enumerated collection rather than using explicit indices.
 
<langsyntaxhighlight lang="python">def cycleSort(vector):
"Sort a vector in place and return the number of writes."
writes = 0
Line 1,391 ⟶ 2,015:
else:
print('%r\nIs correctly sorted using cycleSort to'
'\n%r\nUsing %i writes.' % (x, xcopy, writes))</langsyntaxhighlight>
 
{{out}}
Line 1,400 ⟶ 2,024:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket/base
(require racket/match)
 
Line 1,441 ⟶ 2,065:
(define B #(1 1 1 1 1 1))
B
(cycle-sort! B < =))</langsyntaxhighlight>
 
{{out}}
Line 1,452 ⟶ 2,076:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>sub cycle_sort ( @nums ) {
my $writes = 0;
 
Line 1,492 ⟶ 2,116:
say 'writes ', cycle_sort(@a);
say @a;
</syntaxhighlight>
</lang>
{{out}}
<pre>0 1 2 2 2 2 1 9 3.5 5 8 4 7 0 6
Line 1,501 ⟶ 2,125:
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* 12.06.2014 Walter Pachl translated from Wikipedia's code
* 20.06.2014 WP corrected (courtesy Alan Sampson)
Line 1,563 ⟶ 2,187:
End
End
return writes</langsyntaxhighlight>
{{out}}
<pre>1 9 3 5 8 4 7 0 6 2
Line 1,570 ⟶ 2,194:
 
===version 2===
This REXX version demonstrates the use of negative numbers and non-integeralso non─integer values in the list.
 
As a default, the program uses (for the input list) some digits of pi, which for practical purposes, appear random.
<langsyntaxhighlight lang="rexx">/*REXX program demonstratesperforms a cycle sort on a list of items. (could be numbers or text).*/
parse arg z /*obtain [↓]optional notarguments specified?from the Use "pi" digits.CL*/
if z='' then z= -3.14 3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4 6 2 6 4 3 3 8 3 2 7 9 5 0 2 8 8 4
say 'unsorted list: ' z /*show the original unsorted numbers. */
w= sortCycle(z) /*W: the number of writes done in sort*/
say 'and took sorted list: ' wy "writes." /*show number of writesthe doneoriginal inunsorted sortnumbers. */
say 'and required ' w " writes." /*show number of writes done in sort. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sortCycle: procedure expose @.y; parse arg y; #= words(y); mv= 0 /*MV: #=words(y); moves or writes=0*/
do i=1 for #; @.i= word(y,i); end /*i*/ /*put each of the items ───► @. array.*/
end /*i*/ /* [↓] find a "cycle" to rotate. */
do c=1 for #; x=@.c; p=c c /*X is the item being sorted. */
do j=c+1 to #; if @.j<x then p= p + 1; end /*determine where to put X. into array @*/
end /*j*/
if p==c then iterate /*Is it there? No, this ain't a cycle.*/
if p==c then iterate do while x==@.p; p=p+1; end /*put X right after any/*Is duplicate.it there? No, this ain't a cycle.*/
parsecall value.putX @.p x with x @.p /*swap the two values: @.p and /*put X right after any dups; swap. */
writes=writes+1 do while p\==c; p= c /*bumprotate counterthe forrest of the number"cycle". of writes*/
do while p\==c; do pk=c+1 to #; if @.k<x then p= p+1 /*rotatedetermine thewhere restto ofput thethis "cycle"element. */
do k=c+1end to #; if @.k<x then p=p+1; end /*k*/
call .putX do while x==@.p; p=p+1; end /*put X here or /*put X right after any dups.; swap. */
end /*while p\==c*/
parse value @.p x with x @.p /*swap the two values: @.p and X.*/
writes=writes+1 /*bump the counter for number of writes*/
end /*while p\==c*/
end /*c*/
y=@.1; do m=2 for #-1; y=y @.m; end; return mv /*put the array back into the Y list.*/
/* [↓] display the sorted list. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
_=@.1; do j=2 to #; _=_ @.j; end; say ' sorted list: ' _
.putX: mv= mv+1; do p=p while x==@.p; end; parse value @.p x with x @.p; return</syntaxhighlight>
return writes</lang>
'''{{out|output''' |text=&nbsp; when using the default input:}}
<pre>
unsorted list: -3.14 3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4 6 2 6 4 3 3 8 3 2 7 9 5 0 2 8 8 4
sorted list: -3.14 0 1 1 2 2 2 2 2 3 3 3 3 3 3 3 4 4 4 4 5 5 5 5 6 6 6 7 7 8 8 8 8 8 9 9 9 9
and tookrequired 34 writes.
</pre>
'''{{out|output''' |text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> FM Stereo has been around since 1961. </tt>}}
<pre>
unsorted list: FM Stereo has been around since 1961.
sorted list: 1961. FM Stereo around been has since
and tookrequired 7 writes.
</pre>
Note (for the above output). &nbsp; This REXX program was executed on an '''ASCII''' machine.
<br>On an &nbsp; '''ASCII''' &nbsp; machine, the order of sorting is numbers, uppercase letters, lowercase letters.<br>
On an '''EBCDIC''' machine, the order of sorting is lowercase letters, uppercase letters, numbers.<br>
Other (special) characters may also be in a different order. <br><br>
 
===version 3===
This version uses a faster (but a more cryptic) version of incrementing &nbsp; '''1''' &nbsp; (one) to &nbsp; '''P''' &nbsp; within two '''do''' loops.
<lang rexx>/*REXX program demonstrates a cycle sort on a list of items. */
parse arg z /* [↓] not specified? Use "pi" digits.*/
if z='' then z=-3.14 3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4 6 2 6 4 3 3 8 3 2 7 9 5 0 2 8 8 4
say 'unsorted list: ' z /*show the original unsorted numbers. */
w=sortCycle(z) /*W: the number of writes done in sort*/
say 'and took' w "writes." /*show number of writes done in sort. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sortCycle: procedure expose @.; parse arg y; #=words(y); writes=0
do i=1 for #; @.i=word(y,i); end /*i*/ /*put each of the items ───► @. array.*/
/* [↓] find a "cycle" to rotate. */
do c=1 for #; x=@.c; p=c /*X is the item being sorted. */
do j=c+1 to #; if @.j<x then p=p+1; end /*determine where to put X. */
if p==c then iterate /*Is it there? No, this ain't a cycle.*/
do while x==@.p; p=p+1; end /*put X right after any duplicate. */
parse value @.p x with x @.p /*swap the two values: @.p and X.*/
writes=writes+1 /*bump counter for the number of writes*/
do while p\==c; p=c /*rotate the rest of the "cycle". */
do k=c+1 to #; if @.k<x then p=p+1; end /*k*/
do p=p while x==@.p; end /*put X here or right after dups.*/
parse value @.p x with x @.p /*swap the two values: @.p and X.*/
writes=writes+1 /*bump the counter for number of writes*/
end /*while p\==c*/
end /*c*/
/* [↓] display the sorted list. */
_=@.1; do j=2 to #; _=_ @.j; end; say ' sorted list: ' _
return writes</lang>
'''output''' is identical to the 2<sup>nd</sup> version.
 
===version 4===
This version uses a subroutine to perform the task of handling an (sorted) item placement (possibly after duplicates).
<lang rexx>/*REXX program demonstrates a cycle sort on a list of items. */
parse arg z /* [↓] not specified? Use "pi" digits.*/
if z='' then z=-3.14 3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4 6 2 6 4 3 3 8 3 2 7 9 5 0 2 8 8 4
say 'unsorted list: ' z /*show the original unsorted numbers. */
w=sortCycle(z) /*W: the number of writes done in sort*/
say 'and took' w "writes." /*show number of writes done in sort. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sortCycle: procedure expose @.; parse arg y; #=words(y); w=0
do i=1 for #; @.i=word(y,i); end /*i*/ /*put each of the items ───► @. array.*/
 
do c=1 for #; x=@.c; p=c /*X is the item being sorted. */
do j=c+1 to #; if @.j<x then p=p+1; end /*j*/ /*where to put X.*/
if p==c then iterate /*Is it there? Then this ain't a cycle*/
call .swap /*put X here or right after dups.*/
do while p\==c; p=c /*rotate the rest of the "cycle". */
do k=c+1 to #; if @.k<x then p=p+1; end /*k*/
call .swap /*put X here or right after dups.*/
end /*while p\==c*/
end /*c*/
/* [↓] display the sorted list to term*/
_=@.1; do j=2 to #; _=_ @.j; end; say ' sorted list: ' _
return w /* [↓] find where to put X into @ */
.swap: do p=p while x==@.p; end; parse value @.p x with x @.p; w=w+1; return</lang>
'''output''' &nbsp; is identical to the 2<sup>nd</sup> version.
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Sorting algorithms/Cycle sort
 
Line 1,739 ⟶ 2,303:
next
see nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,753 ⟶ 2,317:
=={{header|Ruby}}==
Direct translation of the pseudocode on the Wikipedia.
<langsyntaxhighlight lang="ruby">def cycleSort!(array)
writes = 0
Line 1,794 ⟶ 2,358:
p a = [0, 1, 2, 2, 2, 2, 1, 9, 3.5, 5, 8, 4, 7, 0, 6]
puts "writes : #{cycleSort!(a)}"
p a</langsyntaxhighlight>
 
{{out}}
Line 1,805 ⟶ 2,369:
=={{header|Scala}}==
Translation of Java version
<langsyntaxhighlight lang="scala">
def cycleSort(a: Array[Int]): (Array[Int], Int) = {
var writes = 0
Line 1,848 ⟶ 2,412:
(a, writes)
}
</syntaxhighlight>
</lang>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func cycle_sort (array) {
var (writes=0, pos=0)
 
func f(i, Ref item, bool=false) {
pos = (i + array.ftslice(i+1).count{ _ < *item })
return(false) if (bool && pos==i)
while (*item == array[pos]) { ++pos }
Line 1,865 ⟶ 2,429:
array.each_kv { |i, item|
f(i, \item, true) || next
while (pos  != i) {
f(i, \item)
}
Line 1,877 ⟶ 2,441:
say a.join(' ')
say ('writes ', cycle_sort(a))
say a.join(' ')</langsyntaxhighlight>
{{out}}
<pre>
Line 1,887 ⟶ 2,451:
=={{header|Tcl}}==
Direct translation of the pseudocode on the Wikipedia page
<langsyntaxhighlight lang="tcl">proc cycleSort {listVar} {
upvar 1 $listVar array
set writes 0
Line 1,934 ⟶ 2,498:
return $writes
}</langsyntaxhighlight>
'''Demonstrating:'''
<langsyntaxhighlight lang="tcl">set example {0 1 2 2 2 2 1 9 3.5 5 8 4 7 0 6}
puts "Data was: $example"
set writes [cycleSort example]
Line 1,945 ⟶ 2,509:
puts "\twhich is the wrong order!"
}
puts "Writes required: $writes"</langsyntaxhighlight>
{{out}}
<pre>
Line 1,953 ⟶ 2,517:
Writes required: 10
</pre>
 
=={{header|Wren}}==
Translation of the Python code in the Wikipedia article.
<syntaxhighlight lang="wren">var cycleSort = Fn.new { |a|
var writes = 0
var len = a.count
for (cs in 0...len-1) {
var item = a[cs]
var pos = cs
for (i in cs+1...len) {
if (a[i] < item) pos = pos + 1
}
if (pos != cs) {
while (item == a[pos]) pos = pos + 1
var t = a[pos]
a[pos] = item
item = t
while (pos != cs) {
pos = cs
for (i in cs+1...len) {
if (a[i] < item) pos = pos + 1
}
while (item == a[pos]) pos = pos + 1
var t = a[pos]
a[pos] = item
item = t
writes = writes + 1
}
}
}
return writes
}
 
var array = [ [4, 65, 2, -31, 0, 99, 2, 83, 782, 1], [7, 5, 2, 6, 1, 4, 2, 6, 3] ]
for (a in array) {
System.print("Before : %(a)")
var w = cycleSort.call(a)
System.print("After : %(a)")
System.print("Writes : %(w)")
System.print()
}</syntaxhighlight>
 
{{out}}
<pre>
Before : [4, 65, 2, -31, 0, 99, 2, 83, 782, 1]
After : [-31, 0, 1, 2, 2, 4, 65, 83, 99, 782]
Writes : 7
 
Before : [7, 5, 2, 6, 1, 4, 2, 6, 3]
After : [1, 2, 2, 3, 4, 5, 6, 6, 7]
Writes : 6
</pre>
 
=={{header|XPL0}}==
{{trans|Wren}}
<syntaxhighlight lang "XPL0">func CycleSort(A, Len);
int A, Len;
int Writes, I, J, Item, Pos, T;
[Writes:= 0;
for J:= 0 to Len-2 do
[Item:= A(J);
Pos:= J;
for I:= J+1 to Len-1 do
if A(I) < Item then Pos:= Pos+1;
if Pos # J then
[while Item = A(Pos) do Pos:= Pos+1;
T:= A(Pos); A(Pos):= Item; Item:= T;
while Pos # J do
[Pos:= J;
for I:= J+1 to Len-1 do
if A(I) < Item then Pos:= Pos+1;
while Item = A(Pos) do Pos:= Pos+1;
T:= A(Pos); A(Pos):= Item; Item:= T;
Writes:= Writes+1;
];
];
];
return Writes;
];
 
int As, Lens, A, W, I;
[As:= [ [4, 65, 2, -31, 0, 99, 2, 83, 782, 1],
[7, 5, 2, 6, 1, 4, 2, 6, 3] ];
Lens:= [10, 9];
for A:= 0 to 2-1 do
[Text(0, "Before : [");
for I:= 0 to Lens(A)-1 do
[IntOut(0, As(A,I));
Text(0, if I = Lens(A)-1 then "]^m^j" else ", ");
];
W:= CycleSort(As(A), Lens(A));
Text(0, "After : [");
for I:= 0 to Lens(A)-1 do
[IntOut(0, As(A,I));
Text(0, if I = Lens(A)-1 then "]^m^j" else ", ");
];
Text(0, "Writes : "); IntOut(0, W); CrLf(0); CrLf(0);
];
]</syntaxhighlight>
{{out}}
<pre>
Before : [4, 65, 2, -31, 0, 99, 2, 83, 782, 1]
After : [-31, 0, 1, 2, 2, 4, 65, 83, 99, 782]
Writes : 7
 
Before : [7, 5, 2, 6, 1, 4, 2, 6, 3]
After : [1, 2, 2, 3, 4, 5, 6, 6, 7]
Writes : 6
 
</pre>
 
=={{header|Yabasic}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="yabasic">// Rosetta Code problem: http://rosettacode.org/wiki/Cycle_sort
// by Galileo, 04/2022
 
sub cyclesort(array())
local writes, lenarray, item, pos, i, prov
lenarray = arraysize(array(), 1)
for cyclestart = 1 to lenarray
item = array(cyclestart)
pos = cyclestart
for i = cyclestart + 1 to lenarray
if array(i) < item pos = pos + 1
next
if pos = cyclestart continue
while item = array(pos)
pos = pos + 1
wend
prov = array(pos) : array(pos) = item : item = prov
writes = writes + 1
while pos != cyclestart
pos = cyclestart
for i = cyclestart + 1 to lenarray
if array(i) < item pos = pos + 1
next
while item = array(pos)
pos = pos + 1
wend
prov = array(pos) : array(pos) = item : item = prov
writes = writes + 1
wend
next
return writes
end sub
 
sub printArray(array())
local i
for i = 1 to arraysize(array(), 1)
print array(i), " ";
next
print
end sub
 
 
dim ints(10)
 
for i = 1 to 10
ints(i) = int(ran(10))
next
 
printArray(ints())
print "writes ", cyclesort(ints())
printArray(ints())</syntaxhighlight>
{{out}}
<pre>9 9 9 6 8 1 9 7 3 4
writes 8
1 3 4 6 7 8 9 9 9 9
---Program done, press RETURN---</pre>
9,476

edits