1. Cycle start
Try to place the value at each starting position into its final rank.
for (let cycleStart = 0; cycleStart < arr.length - 1; cycleStart++)Typorithm · hard
Step 1 of 8 · intro card
Sorting Algorithms
Cycle Sort places each value into its final rank while trying to minimize the number of writes.
Cycle Sort is designed for situations where writes are expensive.
For each cycle start, it counts how many values are smaller than the held item.
That count tells the position where the item belongs.
The algorithm writes the item there, then repeats with the displaced item until the cycle closes.
It performs O(n^2) comparisons but can use very few writes.
Count smaller values to find final position.
Skip if the item is already placed.
Handle duplicates by stepping past equals.
Close each write cycle before moving on.
Optimizes writes, not comparisons.
function cycleSort(arr) {
for (let cycleStart = 0; cycleStart < arr.length - 1; cycleStart++) {
let item = arr[cycleStart];
let position = cycleStart;
for (let i = cycleStart + 1; i < arr.length; i++) {
if (arr[i] < item) position++;
}
if (position === cycleStart) continue;
while (item === arr[position]) position++;
[arr[position], item] = [item, arr[position]];
while (position !== cycleStart) {
position = cycleStart;
for (let i = cycleStart + 1; i < arr.length; i++) {
if (arr[i] < item) position++;
}
while (item === arr[position]) position++;
[arr[position], item] = [item, arr[position]];
}
}
return arr;
}Connect each part of the code to the concept before you type.
Try to place the value at each starting position into its final rank.
for (let cycleStart = 0; cycleStart < arr.length - 1; cycleStart++)Hold the value that may be written into its correct position.
let item = arr[cycleStart]position counts how many values are smaller than item.
let position = cycleStartEvery smaller value means item belongs one index farther right.
if (arr[i] < item) position++Skip writing when the item is already in the correct position.
if (position === cycleStart) continueMove past equal values so duplicate keys do not overwrite each other.
while (item === arr[position]) position++Place item and hold the value displaced from that position.
[arr[position], item] = [item, arr[position]]Keep placing displaced items until the cycle returns to the start.
while (position !== cycleStart)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
Input[5,1,4,2,8]
One temporary value and a fixed number of indices. In-place does not mean zero extra memory. The input array is not counted as extra space.
One reusable value slot. Empty until the next operation needs it.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state