How cycle sort writes each item to its final index

Short answer: Cycle sort follows the cycle that a permutation forms and writes each misplaced item directly to the index its rank names. Items already in place are left untouched. The comparison count stays Θ(n²), because each rank is computed by scanning. The point of the algorithm is the write pattern: a destination is written when an item arrives there, which is as few data writes as a cycle decomposition allows.


What the problem actually asks

Selection sort also hunts for the item that belongs in the next slot, and it does so with about n swaps. Inside one swap, the item that was sitting in that slot is thrown somewhere it may not belong, and a later pass must move it again. A permutation is a set of cycles. Rotating a cycle sends every member to its final index in a single trip.

The rank of an item is the number of items that must stand strictly before it. Computing that rank from scratch is a scan. The writes become cheap and the comparisons do not.


What the algorithm guarantees

Every item either already sits at its final index or is written there during the rotation of its cycle. A cycle of length L is resolved by holding one item in a register and writing each following item into the hole, which is L writes of records into their destinations. Fixed points are not written. Extra memory is the register and a few indices. Time is Θ(n²) comparisons in every case, because each cycle start scans the suffix to recompute ranks.

Duplicates need an explicit skip: if several items share a key, the first free index at that rank is the one that is still holding a different key. The standard treatment of duplicates is unstable. A write-minimal stable sort is a different, heavier construction.


The working steps

  1. For cycle_start from 0 to n−2, take the item at that index as the start of a cycle.
  2. Count how many items in the whole array belong strictly before it. That count is its destination.
  3. If the destination equals cycle_start, the item is a fixed point. Continue.
  4. If the destination already holds an equal key, advance to the next duplicate’s slot so a finished equal is left alone.
  5. Write the held item into the destination and pick up whatever was there. Recompute that new item’s rank the same way. Stop the cycle when the write returns to cycle_start.

The quadratic scans are the cost of discovering ranks with comparisons alone. When keys are integers in a small range, counting sort writes each record once into an output buffer in linear time and does not need this cycle walk. Cycle sort is what remains when the only legal mutation is a write into the same array and the number of those writes must stay minimal.


Approaches that look simpler and fail

Approach Why it fails when each item may be written only to its final slot
Selection sort The displaced item is swapped into the minimum’s old slot, which is rarely its own destination. Later passes write it again.
A cycle walk that does not recompute ranks after duplicates Two equal keys claim one index. The second write lands on a finished item or leaves a hole.
Treat the write bound as a time bound Rank finding scans the array. Time stays quadratic on every input, including a sorted one, unless fixed points are detected and the scan is still paid by the items that move.
Expect stability Items of equal key are assigned destinations by the order the scans discover them. That assignment does not preserve input order.

Few writes into a separate output array, with linear time, belong to counting sort when the key range allows it. A general comparison sort that is willing to write Θ(n log n) times belongs to heapsort.


A working example

The Bash script and the Python script cycle-sort. Each misplaced item is written to the index where it belongs. Both print 1 2 3 4 8 9.

a=(4 2 3 1 8 9)
n=${#a[@]}
for ((start=0; start<n-1; start++)); do
  item=${a[start]}
  pos=$start
  for ((i=start+1; i<n; i++)); do
    if (( a[i] < item )); then pos=$((pos+1)); fi
  done
  if (( pos == start )); then continue; fi
  while (( a[pos] == item )); do pos=$((pos+1)); done
  t=${a[pos]}; a[pos]=$item; item=$t
  while (( pos != start )); do
    pos=$start
    for ((i=start+1; i<n; i++)); do
      if (( a[i] < item )); then pos=$((pos+1)); fi
    done
    while (( a[pos] == item )); do pos=$((pos+1)); done
    t=${a[pos]}; a[pos]=$item; item=$t
  done
done
echo "${a[*]}"
def cycle_sort(a):
    a = a[:]
    for start in range(len(a) - 1):
        item = a[start]
        pos = start + sum(1 for i in range(start + 1, len(a)) if a[i] < item)
        if pos == start:
            continue
        while a[pos] == item:
            pos += 1
        a[pos], item = item, a[pos]
        while pos != start:
            pos = start + sum(1 for i in range(start + 1, len(a)) if a[i] < item)
            while a[pos] == item:
                pos += 1
            a[pos], item = item, a[pos]
    return a

out = cycle_sort([4, 2, 3, 1, 8, 9])
assert out == [1, 2, 3, 4, 8, 9]
print(*out)

Where it is used

Cycle sort writes each item directly to its final index, which is the point when a write is expensive, as on an EEPROM or a flash page. The number of writes is optimal. A library sort that may rewrite an item several times is the wrong tool for that memory.


When you can drop this algorithm

Drop cycle sort when CPU time matters more than writes. Almost any n log n sort is faster. Keep it when each write to the data array is the scarce resource and a quadratic number of comparisons is acceptable, which includes some teaching cases and some write-limited memories.


Why this stays published

We publish this so a search for cycle sort returns the cycle write pattern and the quadratic rank scans as two different costs. Cycle sort writes each misplaced item to the index its rank names, and it spends a quadratic number of comparisons to discover those ranks.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *