Sorting algorithms/Cycle sort: Difference between revisions

m
→‎{{header|Wren}}: 'as' is now a keyword.
m (→‎{{header|Wren}}: 'as' is now a keyword.)
 
(9 intermediate revisions by 8 users not shown)
Line 24:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F cycleSort(&vector)
V writes = 0
 
Line 62:
E
print("#.\nIs correctly sorted using cycleSort to".format(x))
print("#.\nUsing #. writes.".format(xcopy, writes))</langsyntaxhighlight>
 
{{out}}
Line 75:
{{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 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}}==
 
<langsyntaxhighlight lang="rebol">cycleSort: function [items][
a: new items
position: 0
Line 224 ⟶ 474:
]
 
print cycleSort [3 1 2 8 5 7 9 4 6]</langsyntaxhighlight>
 
{{out}}
Line 231 ⟶ 481:
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
// Sort an array in place and return the number of writes
Line 289 ⟶ 539:
writes("After: ") ; writevec(v, l)
writef("Writes: %N*N", w)
$)</langsyntaxhighlight>
{{out}}
<pre>Before: 0 1 2 2 2 2 1 9 3 5 5 8 4 7 0 6
Line 297 ⟶ 547:
=={{header|C}}==
{{trans|NetRexx}}
<syntaxhighlight lang="c">
<lang C>
#include <stdio.h>
#include <stdlib.h>
Line 395 ⟶ 645:
return;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 405 ⟶ 655:
=={{header|C++}}==
Based on example code on Wikipedia
<syntaxhighlight lang="cpp">
<lang Cpp>
#include <time.h>
#include <iostream>
Line 471 ⟶ 721:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 482 ⟶ 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 536 ⟶ 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 545 ⟶ 795:
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule Sort do
def cycleSort(list) do
tuple = List.to_tuple(list)
Line 587 ⟶ 837:
{b, writes} = Sort.cycleSort(a)
IO.puts "writes : #{writes}"
IO.inspect b</langsyntaxhighlight>
 
{{out}}
Line 598 ⟶ 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 666 ⟶ 916:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 682 ⟶ 932:
This implementation was translated from the example code on Wikipedia.
 
<langsyntaxhighlight lang="go">package main
 
import (
Line 744 ⟶ 994:
fmt.Printf("writes %d\n", cyclesort(ints))
fmt.Println(ints)
}</langsyntaxhighlight>
 
{{out}}
Line 757 ⟶ 1,007:
=={{header|Groovy}}==
{{trans|Java}}
<langsyntaxhighlight 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]
Line 821 ⟶ 1,071:
return writes
}
}</langsyntaxhighlight>
{{out}}
<pre>[5, 0, 1, 2, 2, 3, 5, 1, 1, 0, 5, 6, 9, 8, 0, 1]
Line 832 ⟶ 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 842 ⟶ 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 867 ⟶ 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 879 ⟶ 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 903 ⟶ 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 973 ⟶ 1,223:
return writes;
}
}</langsyntaxhighlight>
 
{{out}}
Line 987 ⟶ 1,237:
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">
<lang jq>
# Output: {a: sortedInput, write: numberOfSwaps}
def cycleSort:
Line 1,009 ⟶ 1,259:
else .
end )
| {a, writes} ;</langsyntaxhighlight>
'''The Task'''
<langsyntaxhighlight 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]
Line 1,018 ⟶ 1,268:
| "After : \(.a)",
"Writes : \(.writes)",
"")</langsyntaxhighlight>
{{out}}
<pre>
Line 1,038 ⟶ 1,288:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">function cyclesort!(v::Vector)
writes = 0
for (cyclestart, item) in enumerate(v)
Line 1,070 ⟶ 1,320:
 
v = rand(-10:10, 10)
println("# unordered: $v\n -> ordered: ", cyclesort!(v))</langsyntaxhighlight>
 
{{out}}
Line 1,078 ⟶ 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 1,136 ⟶ 1,386:
val array4 = "sphinx of black quartz judge my vow".replace(" ", "").toCharArray().distinct().toTypedArray()
printResults(array4)
}</langsyntaxhighlight>
 
{{out}}
Line 1,159 ⟶ 1,409:
=={{header|Lua}}==
{{trans|Java}}
<langsyntaxhighlight lang="lua">function printa(a)
io.write("[")
for i,v in ipairs(a) do
Line 1,232 ⟶ 1,482:
printa(arr)
print()
print("writes: " .. writes)</langsyntaxhighlight>
{{out}}
<pre>[5, 0, 1, 2, 2, 3, 5, 1, 1, 0, 5, 6, 9, 8, 0, 1]
Line 1,240 ⟶ 1,490:
=={{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 1,318 ⟶ 1,568:
end i_
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,342 ⟶ 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,398 ⟶ 1,648:
writes = array5.cycleSort()
echo "Sorted: ", $array5
echo "Total number of writes: ", writes</langsyntaxhighlight>
 
{{out}}
Line 1,423 ⟶ 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,477 ⟶ 1,727:
return writes;
}
}</langsyntaxhighlight>
 
<pre>
Line 1,486 ⟶ 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,550 ⟶ 1,800:
Say format(i,2) a.i
End
Return</langsyntaxhighlight>
{{out}}
<pre>
Line 1,572 ⟶ 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,619 ⟶ 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,628 ⟶ 1,878:
{{trans|NetRexx}}
plus some factoring out of common code
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 1,690 ⟶ 1,940:
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,716 ⟶ 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,765 ⟶ 2,015:
else:
print('%r\nIs correctly sorted using cycleSort to'
'\n%r\nUsing %i writes.' % (x, xcopy, writes))</langsyntaxhighlight>
 
{{out}}
Line 1,774 ⟶ 2,024:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket/base
(require racket/match)
 
Line 1,815 ⟶ 2,065:
(define B #(1 1 1 1 1 1))
B
(cycle-sort! B < =))</langsyntaxhighlight>
 
{{out}}
Line 1,826 ⟶ 2,076:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>sub cycle_sort ( @nums ) {
my $writes = 0;
 
Line 1,866 ⟶ 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,875 ⟶ 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,937 ⟶ 2,187:
End
End
return writes</langsyntaxhighlight>
{{out}}
<pre>1 9 3 5 8 4 7 0 6 2
Line 1,947 ⟶ 2,197:
 
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 performs a cycle sort on a list of items (could be numbers or text).*/
parse arg z /*obtain optional arguments from the 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
Line 1,972 ⟶ 2,222:
y=@.1; do m=2 for #-1; y=y @.m; end; return mv /*put the array back into the Y list.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
.putX: mv= mv+1; do p=p while x==@.p; end; parse value @.p x with x @.p; return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 1,991 ⟶ 2,241:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Sorting algorithms/Cycle sort
 
Line 2,053 ⟶ 2,303:
next
see nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,067 ⟶ 2,317:
=={{header|Ruby}}==
Direct translation of the pseudocode on the Wikipedia.
<langsyntaxhighlight lang="ruby">def cycleSort!(array)
writes = 0
Line 2,108 ⟶ 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 2,119 ⟶ 2,369:
=={{header|Scala}}==
Translation of Java version
<langsyntaxhighlight lang="scala">
def cycleSort(a: Array[Int]): (Array[Int], Int) = {
var writes = 0
Line 2,162 ⟶ 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 2,179 ⟶ 2,429:
array.each_kv { |i, item|
f(i, \item, true) || next
while (pos  != i) {
f(i, \item)
}
Line 2,191 ⟶ 2,441:
say a.join(' ')
say ('writes ', cycle_sort(a))
say a.join(' ')</langsyntaxhighlight>
{{out}}
<pre>
Line 2,201 ⟶ 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 2,248 ⟶ 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 2,259 ⟶ 2,509:
puts "\twhich is the wrong order!"
}
puts "Writes required: $writes"</langsyntaxhighlight>
{{out}}
<pre>
Line 2,270 ⟶ 2,520:
=={{header|Wren}}==
Translation of the Python code in the Wikipedia article.
<langsyntaxhighlight ecmascriptlang="wren">var cycleSort = Fn.new { |a|
var writes = 0
var len = a.count
Line 2,300 ⟶ 2,550:
}
 
var asarray = [ [4, 65, 2, -31, 0, 99, 2, 83, 782, 1], [7, 5, 2, 6, 1, 4, 2, 6, 3] ]
for (a in asarray) {
System.print("Before : %(a)")
var w = cycleSort.call(a)
Line 2,307 ⟶ 2,557:
System.print("Writes : %(w)")
System.print()
}</langsyntaxhighlight>
 
{{out}}
Line 2,319 ⟶ 2,569:
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