Statistics
Controls
Summary
Cycle Sort is a comparison-based algorithm designed to minimize the total number of memory writes. It works by decomposing the array into a set of "cycles". For each element, the algorithm calculates its correct final position by counting how many elements in the array are smaller than it. It then places the element into that position, displacing the element that was previously there. This displaced element is then moved to its correct position, and the process repeats until the cycle returns to the starting point.
How it Works
-
Iterate through the array starting from
cycleStart = 0ton-2. -
Store the element at
cycleStartin a temporary variable calleditem. -
Find Rank: Scan all elements to the right of
cycleStart. Count how many elements are smaller thanitem. This count added tocycleStartgives the correctpos(position) foritem. -
Skip Duplicates: If
itemis equal to the element currently atpos, incrementposto placeitemafter the duplicates. -
Write: If
posis different fromcycleStart, writeitemtoarr[pos]. The value originally atarr[pos]becomes the newitemto be placed. -
Rotate Cycle: Repeat the find-rank and write process for the new
itemuntilposequalscycleStart. -
Move to the next
cycleStartand repeat.