Cycle Sort Python (original) (raw)

Last Updated : 24 Dec, 2025

Cycle Sort is an in-place sorting algorithm that minimizes the number of write operations by placing each element directly into its correct position. It is mainly used when write operations are costly, such as in memory-constrained systems.

Cycle in arr[] = {2, 4, 5, 1, 3}:

Cycle-sort

Illustration of Cycles

Algorithm Steps

  1. Start from the first element and determine its correct position in the sorted array.
  2. Place the element in its correct position. If this displaces another element, continue rotating the displaced elements until the cycle is complete.
  3. Repeat for the next element not yet in its correct position.
  4. Continue until the entire array is sorted.

Dry Run of the Cycle Sort

Initial Array: [4, 3, 1, 2]

Cycle Start 0: item = 4

Array after Cycle 0: [1, 2, 3, 4]

Cycle Start 1: item = 2 -> already in correct position, skip
Cycle Start 2: item = 3 -> already in correct position, skip
Cycle Start 3: item = 4 -> already in correct position, skip

Sorted Array: [1, 2, 3, 4]

Python Implementation

Python `

arr = [4,3,1,2] writes = 0 n = len(arr)

for cycleStart in range(0, n - 1): item = arr[cycleStart]

pos = cycleStart
for i in range(cycleStart + 1, n):
    if arr[i] < item:
        pos += 1

if pos == cycleStart:
    continue

while item == arr[pos]:
    pos += 1
arr[pos], item = item, arr[pos]
writes += 1

while pos != cycleStart:
    
    pos = cycleStart
    for i in range(cycleStart + 1, n):
        if arr[i] < item:
            pos += 1

    while item == arr[pos]:
        pos += 1
    arr[pos], item = item, arr[pos]
    writes += 1

print("After sort : ") for i in range(n): print(arr[i], end=' ')

`

Output

After sort : 1 2 3 4

**Explanation: