
Less common algorithm: Cycle Sort
Posted on
Cycle Sort can be used to handle special case input, which is consecutive integers, it's a decrease and conquers approach:
The name came from how it approaches the inputs: starting from the leftmost spot and figuring out which number goes there, then recursive call on the remaining elements, which looks like a cycle.
The general template looks like this:
for (let i = 0; i < nums.length; i++) {
while (nums[i] !== i) {
const destinationIndex = nums[i]
if (nums[destinationIndex] !== nums[i]) {
[nums[i], nums[destinationIndex]] = [nums[destinationIndex], nums[i]]
} else {
break
}
}
}
it can reach O(n) on time complexity instead of O(n2) and without the need to use extra space.
To practice on it, you can check the following questions shown on Leetcode:
- Missing Number
- Find All Numbers Disappeared in an Array
- Find the Duplicate Number
- Set Mismatch
- Find All Duplicates in an Array
- First Missing Positive
- Couples Holding Hands