Sorting algorithms/Cycle sort: Difference between revisions

Content added Content deleted
(Rename Perl 6 -> Raku, alphabetize, minor clean-up)
Line 1,257: Line 1,257:
There were 50 writes
There were 50 writes
After sorting: a a b b c c d d e e f f g g h h i i j j k k l l m m n n o o p p q q r r s s t t u u v v w w x x y y z z</pre>
After sorting: a a b b c c d d e e f f g g h h i i j j k k l l m m n n o o p p q q r r s s t t u u v v w w x x y y z z</pre>

=={{header|Perl 6}}==
<lang perl6>sub cycle_sort ( @nums ) {
my $writes = 0;

# Loop through the array to find cycles to rotate.
for @nums.kv -> $cycle_start, $item is copy {

# Find where to put the item.
my $pos = $cycle_start
+ @nums[ $cycle_start ^.. * ].grep: * < $item;

# If the item is already there, this is not a cycle.
next if $pos == $cycle_start;

# Otherwise, put the item there or right after any duplicates.
$pos++ while $item == @nums[$pos];
( @nums[$pos], $item ) .= reverse;
$writes++;

# Rotate the rest of the cycle.
while $pos != $cycle_start {

# Find where to put the item.
$pos = $cycle_start
+ @nums[ $cycle_start ^.. * ].grep: * < $item;

# Put the item there or right after any duplicates.
$pos++ while $item == @nums[$pos];
( @nums[$pos], $item ) .= reverse;
$writes++;
}
}

return $writes;
}

my @a = <0 1 2 2 2 2 1 9 3.5 5 8 4 7 0 6>;

say @a;
say 'writes ', cycle_sort(@a);
say @a;
</lang>
{{out}}
<pre>0 1 2 2 2 2 1 9 3.5 5 8 4 7 0 6
writes 10
0 0 1 1 2 2 2 2 3.5 4 5 6 7 8 9
</pre>


=={{header|Phix}}==
=={{header|Phix}}==
Line 1,497: Line 1,449:
'#(1 1 1 1 1 1)
'#(1 1 1 1 1 1)
0</pre>
0</pre>

=={{header|Raku}}==
(formerly Perl 6)
<lang perl6>sub cycle_sort ( @nums ) {
my $writes = 0;

# Loop through the array to find cycles to rotate.
for @nums.kv -> $cycle_start, $item is copy {

# Find where to put the item.
my $pos = $cycle_start
+ @nums[ $cycle_start ^.. * ].grep: * < $item;

# If the item is already there, this is not a cycle.
next if $pos == $cycle_start;

# Otherwise, put the item there or right after any duplicates.
$pos++ while $item == @nums[$pos];
( @nums[$pos], $item ) .= reverse;
$writes++;

# Rotate the rest of the cycle.
while $pos != $cycle_start {

# Find where to put the item.
$pos = $cycle_start
+ @nums[ $cycle_start ^.. * ].grep: * < $item;

# Put the item there or right after any duplicates.
$pos++ while $item == @nums[$pos];
( @nums[$pos], $item ) .= reverse;
$writes++;
}
}

return $writes;
}

my @a = <0 1 2 2 2 2 1 9 3.5 5 8 4 7 0 6>;

say @a;
say 'writes ', cycle_sort(@a);
say @a;
</lang>
{{out}}
<pre>0 1 2 2 2 2 1 9 3.5 5 8 4 7 0 6
writes 10
0 0 1 1 2 2 2 2 3.5 4 5 6 7 8 9
</pre>


=={{header|REXX}}==
=={{header|REXX}}==