Algorithm Visualiser by Tsvetozar Biserov

Cycle Sort

  • Ω( n2 )
  • Θ( n2 )
  • O( n2 )
  • space O( 1 )

Cycle sort asks one question per element: how many values are smaller than you? The answer is the exact final position, so the element is written straight there, and whatever it overwrote becomes the next element to place. Following these jumps walks around a cycle of the permutation until it closes. No value is ever written to a wrong cell, which makes it the sorting method that writes to memory least, at the cost of a lot of counting.

Array
Comparator strip Index down, time to the right
100 elements
×20 steps/frame

Comparisons 1
—
Reads 2
—
Writes 2
—
Swaps 3
—
Real time 4
—
Visual time 4
—
  1. Comparisons count only element-against-element checks; loop and index checks are never counted.
  2. Reads and writes include reads and writes to helper buffers (merge, counting, radix, bucket and tim sort).
  3. A swap counts once, as a swap. It is never also counted as a read or a write.
  4. Real time is the average time of the counted sort on this device over repeated runs, measured once before playback and independent of animation speed. Visual time is the time spent animating, excluding pauses.

How cycle sort works

Start from 5, 2, 6, 1, 4, 3 and take index 0. The 5 has four smaller values to its right (2, 1, 4, 3), so it belongs at index 4. The algorithm writes it there and picks up the 4 it displaced: [5, 2, 6, 1, 5, 3]. The 5 still sits at index 0 as well, because the value being carried is held in a variable and the start cell is only overwritten when the cycle closes. The 4 has three smaller values (2, 1, 3), so it goes to index 3, giving [5, 2, 6, 4, 5, 3].

The displaced value is now the 1, and it has no smaller value to its right, so its target is index 0, the start of the cycle. Writing it there yields [1, 2, 6, 4, 5, 3] and closes the first cycle with three writes. The 2 at index 1 is already home and costs a count but no write. At index 2 the 6 has three smaller values, so it is written to index 5, producing [1, 2, 6, 4, 5, 6], and the 3 it displaced goes back to index 2 to close a second cycle: [1, 2, 3, 4, 5, 6].

In total there are five writes and no swaps, one for each of the five values that began out of place. Only the 2 was already correct. The cost is on the other side of the ledger: the same run makes 36 comparisons, against 15 for selection sort on this input, because every placement requires another scan over the unsorted part.

Cycle Sort on 5 2 6 1 4 3, one swap or write at a time. Indexes count from 0.
Step Change Array after
1 Write 5 at index 4 5 2 6 1 5 3
2 Write 4 at index 3 5 2 6 4 5 3
3 Write 1 at index 0 1 2 6 4 5 3
4 Write 6 at index 5 1 2 6 4 5 6
5 Write 3 at index 2 1 2 3 4 5 6

All 5 changes are shown.

Pseudocode

for start = 0 to n - 2
  item = a[start]
  pos = start + count of a[j] < item for j > start
  if pos == start
    continue
  skip over values equal to item at pos
  swap item with a[pos]
  while pos != start
    pos = start + count of a[j] < item for j > start
    skip over values equal to item at pos
    swap item with a[pos]

Why these complexities

Each element needs a scan of everything to its right to count the smaller ones, and the loop makes that scan even for elements that turn out to be in place. Sorted input therefore still costs n(n-1)/2 comparisons, 28 for eight elements. When elements are out of place, each one placed starts another scan, so the count can more than double: reversed input of eight elements takes 62. Best, average and worst are all O(n²), with the best case still quadratic.

Writes are the interesting figure. For distinct values the number of writes equals the number of elements that start in the wrong cell, never more than n and zero for sorted input. Each write puts a value into its final position and it is never touched again. No other in-place comparison sort can do better, because an element that is out of place must be written at least once. Selection sort, by contrast, writes two cells per swap.

Space is O(1): the carried value, the target position and the start index. With duplicate values the target alone is ambiguous, because equal values share the same count of smaller ones. The implementation steps past cells that already hold an equal value, and since equality has to be established with two less-than tests, that check adds to the comparison total. Equal values can also end up in a different relative order, so the sort is not stable.

Measured on this site

Exact counts from this site's own engine for 32 elements, using the same rules as the visualiser.

Input Comparisons Writes Swaps
Random 1,351 31 0
Already sorted 496 0 0
Reversed 920 32 0
Few distinct values 1,145 21 0

When to use it

Use it when writes are far more costly than reads, for example on flash memory with limited write endurance. It writes each element at most once, and elements already in place not at all.

Frequently asked questions

Why does cycle sort write so little?

It counts how many elements are smaller to find the exact final position of each one, then writes it straight there.

What does it cost for that?

Time. It needs O(n²) comparisons in every case, even on sorted input.

Is cycle sort stable?

No, not in its usual form. Jumping to the final position can reorder equal elements.

How can I tell in advance how many writes cycle sort will make?

For distinct values, count the elements whose current index differs from their sorted index. That number is exactly the write count. On the six-element input it is five, since only the 2 is in place. A sorted array writes nothing at all, and a reversed array of n elements writes n, or n - 1 when n is odd because the middle element is already home.

What happens with duplicate values?

Equal values have the same number of smaller elements, so counting alone would send them all to one cell and loop forever. After computing the target, the implementation skips past any cell that already holds a value equal to the one being placed. Equality is tested with two less-than comparisons, so duplicates raise the comparison count, and equal elements may be reordered relative to the input.

Background

The method is usually credited to B. K. Haddon, who described it in The Computer Journal in 1990. The underlying observation is older and purely mathematical: any rearrangement of positions splits into disjoint cycles, and each cycle can be applied by moving one value at a time through a single spare slot. Cycle sort applies that fact to sorting by working out the permutation as it goes.

It has never competed with quick sort or merge sort for general use, since quadratic comparisons rule it out for large inputs. Its niche is storage where writing is slow or wears the medium out, such as flash or EEPROM, and cases where the data is small but each write is costly. It also serves as a clean example of an algorithm optimised for a different resource than time.

References

  • Haddon, Cycle-sort: a linear sorting method, The Computer Journal 33(4), 1990
  • Knuth, The Art of Computer Programming, vol. 1, section 1.3.3 (Applications to Permutations)
  • Knuth, The Art of Computer Programming, vol. 3, section 5.2 (Internal Sorting)

Compare with

Algorithm Average time Worst time
Selection Sort Θ( n2 ) O( n2 )
Heap Sort Θ( n log n ) O( n log n )
Pancake Sort Θ( n2 ) O( n2 )
Big O notation
Best time Ω( n2 ) poor
Average time Θ( n2 ) poor
Worst time O( n2 ) poor
Worst space O( 1 ) good

Properties

Stable
No
In place
Yes
Adaptive
No
Comparison-based
Yes