Jump to content

Sorting algorithms/Cycle sort: Difference between revisions

(→‎{{header|Kotlin}}: Updated example see https://github.com/dkandalov/rosettacode-kotlin for details)
Line 932:
Sorted list [George Washington: Virginia, James Madison: Virginia, James Monroe: Virginia, John Adams: Massachusetts, Thomas Jefferson: Virginia]
Total number of writes: 4</pre>
 
=={{header|Objeck}}==
<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];
arr->ToString()->PrintLine();
writes := CycleSort(arr);
"writes: {$writes}"->PrintLine();
arr->ToString()->PrintLine();
}
function : CycleSort(a : Int[]) ~ Int {
writes := 0;
for(cycleStart := 0; cycleStart < a->Size() - 1; cycleStart+=1;) {
val := a[cycleStart];
pos := cycleStart;
for(i := cycleStart + 1; i < a->Size(); i+=1;) {
if(a[i] < val) {
pos++;
};
};
if(pos <> cycleStart) {
while(val = a[pos]) {
pos+=1;
};
tmp := a[pos];
a[pos] := val;
val := tmp;
writes+=1;
 
while(pos <> cycleStart) {
pos := cycleStart;
for(i := cycleStart + 1; i < a->Size(); i+=1;) {
if(a[i] < val) {
pos+=1;
};
};
while(val = a[pos]) {
pos++;
};
tmp := a[pos];
a[pos] := val;
val := tmp;
writes++;
};
};
};
return writes;
}
}</lang>
 
<pre>
[5,0,1,2,2,3,5,1,1,0,5,6,9,8,0,1]
writes: 14
[0,0,0,1,1,1,1,2,2,3,5,5,5,6,8,9]
</pre>
 
=={{header|ooRexx}}==
760

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.