C# Implementation
suggest changepublic static class CycleSort
{
public static void Sort(int[] values)
{
for (int cycleStart = 0; cycleStart < values.Length - 1; cycleStart++)
{
int item = values[cycleStart];
int position = FindPosition(values, cycleStart, item);
if (position == cycleStart) continue;
position = SkipDuplicates(values, position, item);
(values[position], item) = (item, values[position]);
while (position != cycleStart)
{
position = FindPosition(values, cycleStart, item);
position = SkipDuplicates(values, position, item);
(values[position], item) = (item, values[position]);
}
}
}
private static int FindPosition(int[] values, int cycleStart, int item)
{
int position = cycleStart;
for (int index = cycleStart + 1; index < values.Length; index++)
if (values[index] < item) position++;
return position;
}
private static int SkipDuplicates(int[] values, int position, int item)
{
while (item == values[position]) position++;
return position;
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents