Post

Cycle Sort in Java

Learn how Cycle Sort works: its time and space complexity, the algorithm in pseudo code, and a step-by-step visualisation that follows the Java code line by line.

Cycle Sort in Java

Introduction

Cycle Sort is a comparison sort that makes the minimum possible number of writes to the array. Instead of moving values a step at a time, it works out the final position of a value by counting how many values are smaller, and writes it straight there. The value that was in that spot is then placed the same way, and so on, until the chain of moves comes back to where it started.

Three ideas carry the whole algorithm:

  • Final position by counting: a value belongs at cycleStart plus the number of values after cycleStart that are smaller than it.
  • Cycles: every unsorted array splits into cycles: the value at A belongs at B, the value at B belongs at C, …, and one value belongs back at A. Rotating a cycle puts all its values in place.
  • One write per value: each value that isn’t already in place is written exactly once, to its final position. Values that are already in place are never written at all.

Most sorts write far more often than they need to: bubble sort and insertion sort write $O(n^2)$ times. That doesn’t matter in ordinary memory, but it does when writes are expensive or wear out the storage, such as flash memory and EEPROM, where every write shortens the life of a cell. Cycle Sort writes each misplaced value exactly once, so at most $n$ times. That is the minimum possible, since every misplaced value has to be written at least once, and it comes at the cost of a lot of comparisons.

This article uses Cycle Sort with duplicate handling: when the target position already holds an equal value, the value is placed just after it.

Performance Characteristics

Cycle Sort trades comparisons for writes: it always makes about the same, large number of comparisons, but the fewest possible writes.

Time Complexity

Time complexity describes how the number of steps an algorithm takes grows as the input gets larger.

CaseTimeWhen it happens
Best$O(n^2)$An already sorted array: no writes, but every position is still checked by counting
Average$O(n^2)$Random input
Worst$O(n^2)$Any input: finding each position scans the rest of the array

Why $n^2$? Finding the position of a value means comparing it with every value after cycleStart, which is $O(n)$ comparisons. That happens once for each cycleStart, and once more for every value placed during a cycle, so the comparisons add up to $O(n^2)$, whatever the order of the input. The writes are the cheap part: one per misplaced value, so at most $n$, as the visualization’s write counter shows.

Cycle Sort only makes sense when writes are much more expensive than reads or comparisons. For ordinary arrays in memory, it is one of the slowest quadratic sorts, because it also makes $O(n^2)$ comparisons on already sorted input.

Space Complexity

Space complexity describes how much extra memory an algorithm needs, beyond the input itself, as the input gets larger.

PropertyValue
Space$O(1)$: the item being carried and a few indices
In placeYes
StableNo (values are written straight to their place, past equal values)

Algorithm (Pseudo Code)

Cycle Sort goes through the positions from left to right; the current one is cycleStart. It picks up the value there, the item, and counts how many values after cycleStart are smaller. That count, added to cycleStart, is the item’s final position. If it is cycleStart itself, the value is already in place and nothing happens. Otherwise the item is written to its position, and the value that was there is picked up as the new item.

The new item’s position is found the same way, it is written there, and the value it displaces is picked up next. This continues around the cycle, until an item belongs at cycleStart: it is written there, and the cycle is closed. Everything before the next cycleStart is now final, and the same happens for the next position, until the whole array is sorted.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
sort(array):
    for cycleStart = 0 to n - 2:
        item = array[cycleStart]
        pos = findPosition(array, cycleStart, item)
        if pos == cycleStart: continue
        item = placeItem(array, item, pos)
        while pos != cycleStart:
            pos = findPosition(array, cycleStart, item)
            item = placeItem(array, item, pos)

findPosition(array, cycleStart, item):
    pos = cycleStart
    for i = cycleStart + 1 to n - 1:
        if array[i] < item: pos++
    return pos

placeItem(array, item, pos):
    while item == array[pos]: pos++        // skip over equal values
    displaced = array[pos], array[pos] = item
    return displaced

After each value of cycleStart, every position up to and including cycleStart holds its final value, and every write put a value in its final place.

The value at cycleStart is never removed during a cycle; it is only overwritten when the cycle closes. Until then, the array briefly holds that value twice, once at cycleStart and once at its new place, and the item that will close the cycle is carried in the variable item.

Visualization

The visualization below follows the Java code line by line, starting with the values 0 to 9 in shuffled order.

Each step shows the array, the item being carried above it, the pointers and the line of code that is running, with a short explanation of what just happened:

  • Step through: use the arrows to move one step forward or back, or drag the slider to jump to any step.
  • Play: press Play to run the steps automatically, and press it again to pause.
  • Shuffle: press the shuffle button to start again with a new random order.
  • Pointers: C is cycleStart, and P is pos, the position the item belongs at.
  • Item: the amber cell above the array is the item being carried: above the place it came from, or above the position findPosition found for it.
  • Colours: while a position is searched, the smaller values that are counted are amber; a value being written is salmon; and values in their final places are green.
  • Writes: the footer counts the writes. Each value that is not already in place is written exactly once.
  • Duplicates: tick Duplicates to sort values between 0 and 3 with repeats, and see how equal values are skipped.
item / counted written final place C = cycleStart P = pos

Java Code

The implementation is a CycleSort class with one public method, sort, and three private methods: findPosition counts the smaller values to find where an item belongs, placeItem skips over equal values and writes the item, and replace does the actual write and returns the displaced value. One small helper, less, lives in a separate SortUtils class.

The complete code is in the algorithm-examples repository on GitHub: CycleSort.java, with the helpers in SortUtils.java.

sort

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Override
public <T extends Comparable<T>> T[] sort(final T[] array) {
    final int length = array.length;

    for (int cycleStart = 0; cycleStart <= length - 2; cycleStart++) {
        T item = array[cycleStart];
        int pos = findPosition(array, cycleStart, item);

        if (pos == cycleStart) {
            continue;
        }

        item = placeItem(array, item, pos);

        while (pos != cycleStart) {
            pos = findPosition(array, cycleStart, item);
            item = placeItem(array, item, pos);
        }
    }
    return array;
}

sort is the entry point. It accepts an array of any Comparable type and walks cycleStart from the first to the second-to-last position; the last value is in place once all the others are. For each position, it picks up the item and finds where it belongs. If that is cycleStart, the item is already in place. Otherwise it places the item, then keeps placing whatever was displaced, until an item belongs at cycleStart again, which closes the cycle. Empty and one-element arrays skip the loop entirely.

Two details are worth noticing:

  • The loop condition pos != cycleStart checks the position that findPosition returned, before placeItem skips over equal values. That is safe: an item whose position is cycleStart can’t be equal to the value still stored there, because that value’s own position was found to be somewhere else. Run on 20,000 random arrays, half of them full of duplicates, the code sorts every one correctly.
  • findPosition runs again for every displaced item. That is where all the comparisons come from.

findPosition

1
2
3
4
5
6
7
8
9
private <T extends Comparable<T>> int findPosition(final T[] array, final int cycleStart, final T item) {
    int pos = cycleStart;
    for (int i = cycleStart + 1; i < array.length; i++) {
        if (SortUtils.less(array[i], item)) {
            pos++;
        }
    }
    return pos;
}

findPosition counts the values after cycleStart that are strictly smaller than the item. Everything before cycleStart is already final and smaller or equal, so the item’s final position is cycleStart plus that count. Because the comparison is strict, equal values aren’t counted; several equal items get the same position, which is why placeItem has to skip over them.

placeItem and replace

1
2
3
4
5
6
7
8
9
10
11
12
private <T extends Comparable<T>> T placeItem(final T[] array, final T item, int pos) {
    while (item.compareTo(array[pos]) == 0) {
        pos++;
    }
    return replace(array, pos, item);
}

private <T extends Comparable<T>> T replace(final T[] array, final int pos, final T item) {
    final T replacedItem = array[pos];
    array[pos] = item;
    return replacedItem;
}

placeItem moves pos past any values equal to the item, so that equal values fill consecutive positions instead of overwriting each other, and then calls replace. replace writes the item to array[pos] and returns the value it overwrote, which becomes the next item of the cycle. This is the only place where the array is written.

less

1
2
3
public static <T extends Comparable<T>> boolean less(T firstElement, T secondElement) {
    return firstElement.compareTo(secondElement) < 0;
}

This helper from SortUtils keeps findPosition easy to read. less returns true when the first element is smaller than the second, using compareTo, so the algorithm works for any type that implements Comparable.

Running it

1
2
3
4
Integer[] numbers = {7, 2, 9, 4, 0, 8, 3, 6, 1, 5};
new CycleSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Create a CycleSort, pass it an array, and the same array comes back sorted. For this array, every value starts out of place, so the sort makes exactly 10 writes. The class is package-private, so the code must be in the com.javanibble.sort package.

Summary

  • Cycle Sort is a comparison sort that writes every value straight to its final position, found by counting the smaller values.
  • This implementation follows each cycle: it places the item, picks up the displaced value, and repeats until the cycle closes at cycleStart, skipping over equal values on the way.
  • After each cycleStart, every position up to it is final, and each value that wasn’t in place has been written exactly once.
  • It always makes $O(n^2)$ comparisons but only $O(n)$ writes, needs $O(1)$ extra space, and is in place but not stable.
  • Use it when writes are expensive, such as on flash memory. In ordinary memory, almost any other sort is faster.
This post is licensed under CC BY 4.0 by the author.