Cycle Sort
In-place sorting minimizing writes by rotating cycles of elements into position.
Visualization
Interactive visualization for Cycle Sort
Cycle Sort Visualization
Interactive visualization with step-by-step execution
Implementation
1function cycleSort(arr: number[]): number[] {
2 const a = [...arr];
3 const n = a.length;
4 for (let cycleStart = 0; cycleStart < n - 1; cycleStart++) {
5 let item = a[cycleStart];
6 let pos = cycleStart;
7 for (let i = cycleStart + 1; i < n; i++) if (a[i] < item) pos++;
8 if (pos === cycleStart) continue;
9 while (item === a[pos]) pos++;
10 [a[pos], item] = [item, a[pos]];
11 while (pos !== cycleStart) {
12 pos = cycleStart;
13 for (let i = cycleStart + 1; i < n; i++) if (a[i] < item) pos++;
14 while (item === a[pos]) pos++;
15 [a[pos], item] = [item, a[pos]];
16 }
17 }
18 return a;
19}Deep Dive
Theoretical Foundation
For each start index, compute the position of its element by counting smaller elements. If not in place, write it to its position, displacing another element, and continue until the cycle closes.
Complexity
Time
O(n²)
O(n²)
O(n²)
Space
O(1)
Applications
Industry Use
EEPROM/flash with costly writes
Memory-constrained devices
Use Cases
Related Algorithms
Quicksort
A highly efficient, in-place sorting algorithm that uses divide-and-conquer strategy. Invented by Tony Hoare in 1959, it remains one of the most widely used sorting algorithms due to its excellent average-case performance and cache efficiency.
Merge Sort
A stable, divide-and-conquer sorting algorithm with guaranteed O(n log n) performance.
Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping adjacent elements if they are in the wrong order. This process is repeated until the entire array is sorted. Named for the way larger elements 'bubble' to the top (end) of the array.
Insertion Sort
Insertion Sort is a simple, intuitive sorting algorithm that builds the final sorted array one element at a time. It works similarly to how people sort playing cards in their hands - picking each card and inserting it into its correct position among the already sorted cards. Despite its O(n²) time complexity, Insertion Sort is efficient for small datasets and nearly sorted arrays, making it practical for real-world applications.