![]() |
VOOZH | about |
Cycle Sort is an in-place, unstable, comparison-based sorting algorithm that is optimal in terms of the minimum number of memory writes.
Example:
Input: arr[] = [2, 4, 5, 1, 3]
Output: [1,2,3,4,5]
Explanation:
- 2 -> correct index 1
- 4 -> correct index 3
- 5 -> correct index 4
- 1 -> correct index 0
- 3 -> correct index 2
These form cycles: Cycle 1: 2 -> 4 -> 1 -> 2 , Cycle 2: 5 -> 3 -> 5. After rotating these cycles, array becomes: [1, 2, 3, 4, 5]
The main idea is simple:
For every element, count how many elements are smaller than it.
This count gives its correct position in the sorted array.
If the element is not already at its correct position, place it there.
While placing, another element gets displaced -repeat the same process for that element.
This continues until we come back to the starting point, forming a cycle.
1 2 3 4 5
This method is a special optimized version of Cycle Sort that works only when array elements are in the range 1 to N or 0 to N. In this case, we do not need to explicitly detect cycles; instead, we directly place elements at their correct indices using swapping.
If elements are in range 1 to N, then: Correct index of an element = value - 1
Example: 1 -> index 0, 2 -> index 1, …, N -> index N-1
If elements are in range 0 to N, then: Correct index of an element = value itself
1 2 3 4 5