AlgoLab

O(n²)·O(1) space·not stable
645559896316373459948511843281951114277

Starting cycle sort on an array of 20 items.

Starting cycle sort on an array of 20 items.
  1. 1for each starting position from the first to the second-to-last, follow its cycle
  2. 2remember the value here as the one being placed
  3. 3compare it with each later value to count how many are smaller
  4. 4that count is where the value belongs; if it already belongs here, no write is needed, so move to the next starting position
  5. 5skip over any positions already holding an equal value
  6. 6write the value into its position, swapping out whatever was already there, and count that write
  7. 7the displaced value continues the same cycle: count how many other values are smaller than it, skipping over equal values as before
  8. 8write it into its position, swapping out whatever was there, and count that write; repeat until the cycle returns to the starting position
  9. 9the array is fully sorted
Comparisons
0
Writes
0
Accesses
0

Complexity

BestO(n²)
AverageO(n²)
WorstO(n²)
Extra spaceO(1)
StableNo
n² at n=20 predicts 400; this run took 0.

Cycle sort

Cycle sort divides the array into permutation cycles: chains of positions where each value belongs in the next position in the chain. For each position, it counts how many later values are smaller to work out exactly where the value here belongs, then writes it there in one move, displacing whatever value was already occupying that spot, and follows that displaced value around the same cycle until the cycle closes.

When it is the right choice

Cycle sort earns a place whenever writes are drastically more expensive than reads — writing to flash memory with a limited erase-cycle lifetime, for instance — since it makes the theoretical minimum number of writes: one per value that is not already in its final position, and none at all for a value already there. It is a poor general-purpose choice otherwise: it still performs the same O(n²) comparisons as selection sort in every case, sorted or not, so when reads and writes cost about the same it is not competitive with insertion sort or any O(n log n) sort.

How it works

Worth noticing

Cost

Best
O(n²)
Average
O(n²)
Worst
O(n²)
Extra space
O(1)
Stable
No

Worth comparing

All algorithms