Algorithms · Visualized
Cycle Sort
Sorting Algorithms
Seventeen sorting algorithms on the same shuffled data — watch comparisons, swaps, pivots and heaps rearrange bars step by step.
Cycle sort minimizes the number of writes to the array — each element is placed directly into its final sorted position in one move, and the displaced element continues the same 'cycle' until the cycle closes. Time: O(n²) average, O(n²) worst; space: O(1) — in place with the minimum possible number of writes.
Big-O: Best O(n log n) comparison sorts; counting/radix/bucket reach O(n + k) on small integer keys.
Cycle Sort
SortingCycle sort minimizes the number of writes to the array — each element is placed directly into its final sorted position in one move, and the displaced element continues the same 'cycle' until the cycle closes. This is valuable memory writes are expensive, such as on flash or EEPROM storage.
How Cycle Sort Works
- For a starting position, count how many elements in the rest of the array are smaller than the current item — that count plus the start is its correct index.
- If the item is already at its correct index, move to the next start position.
- Otherwise write the item into its correct slot, taking the displaced value as the new item, and recompute its correct index.
- Repeat until the displaced chain returns to the cycle start.
- Move to the next start position; the array ends fully sorted with the minimum possible writes.
Cycle Sort Worked Example
Input: [20, 40, 50, 10, 30]
Start 0, item 20: one smaller element (10) → index 1 → write 20 into slot 1, displaced 40. Item 40: three smaller → index 3 → write 40, displaced 10. Item 10: zero smaller → index 0 → write 10, cycle closed. Start 1: item (now 50 at index 1... ) continues until [10,20,30,40,50].
def cycle_sort(a):
n = len(a)
writes = 0
for start in range(n - 1):
item = a[start]
pos = start + sum(1 for x in a[start + 1:] if x < item)
while item == a[pos]:
pos += 1
if pos == start:
continue
while item != a[pos]:
item, a[pos] = a[pos], item
writes += 1
pos = start + sum(1 for x in a[start + 1:] if x < item)
while item == a[pos]:
pos += 1
return aBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Cycle Sort Time & Space Complexity
When to Use Cycle Sort
- Sorting on EEPROM / flash storage where each write shortens hardware lifespan.
- Situations where minimizing writes matters more than minimizing comparisons.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.