sub cycle_sort ( @nums ) {
my $writes = 0;
for @nums.kv -> $cycle_start, $item is copy {
my $pos = $cycle_start
+ @nums[ $cycle_start ^.. * ].grep: * < $item;
next if $pos == $cycle_start;
$pos++ while $item == @nums[$pos];
( @nums[$pos], $item ) .= reverse;
$writes++;
while $pos != $cycle_start {
$pos = $cycle_start
+ @nums[ $cycle_start ^.. * ].grep: * < $item;
$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;
Output:
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