|
| 1 | +#include <iostream> |
| 2 | +#include <vector> |
| 3 | +using namespace std; |
| 4 | + |
| 5 | +/* |
| 6 | +----------------------------------------------------- |
| 7 | +🌀 Cyclic Sort Algorithm |
| 8 | +----------------------------------------------------- |
| 9 | +📌 Description: |
| 10 | +Cyclic Sort is an in-place algorithm used to sort an |
| 11 | +array containing numbers in the range [1...n] (or [0...n-1]) |
| 12 | +without duplicates. The idea is to place each element |
| 13 | +at its correct index (index = value - 1) by swapping |
| 14 | +until the array is sorted. |
| 15 | +
|
| 16 | +📊 Complexity Analysis: |
| 17 | +- Time Complexity: O(n) |
| 18 | + Each element is swapped at most once to its correct position. |
| 19 | +- Space Complexity: O(1) |
| 20 | + No extra data structures are used, sorting is in-place. |
| 21 | +
|
| 22 | +✅ Applications: |
| 23 | +- Sorting numbers in the range [1...n] |
| 24 | +- Finding missing or duplicate numbers in arrays |
| 25 | +- Common in coding interview problems |
| 26 | +----------------------------------------------------- |
| 27 | +*/ |
| 28 | + |
| 29 | +// Function to perform cyclic sort |
| 30 | +void cyclicSort(vector<int>& nums) { |
| 31 | + int i = 0; |
| 32 | + int n = nums.size(); |
| 33 | + while (i < n) { |
| 34 | + int correctIndex = nums[i] - 1; // correct index for current element |
| 35 | + |
| 36 | + // Swap only if element is in range and not at the right place |
| 37 | + if (nums[i] >= 1 && nums[i] <= n && nums[i] != nums[correctIndex]) { |
| 38 | + swap(nums[i], nums[correctIndex]); |
| 39 | + } else { |
| 40 | + i++; // move to next index if already in correct position |
| 41 | + } |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +// Utility function to print array |
| 46 | +void print(vector<int>& nums) { |
| 47 | + cout << "Sorted array is:" << endl; |
| 48 | + for (auto i : nums) { |
| 49 | + cout << i << " "; |
| 50 | + } |
| 51 | + cout << endl; |
| 52 | +} |
| 53 | + |
| 54 | +// Driver function |
| 55 | +int main() { |
| 56 | + cout << "This is Cyclic Sort implementation." << endl; |
| 57 | + cout << "Cyclic Sort works efficiently when numbers are in the range [1...n] or [0...n-1] without duplicates." << endl; |
| 58 | + |
| 59 | + int n; |
| 60 | + cout << "Enter value of n: "; |
| 61 | + cin >> n; |
| 62 | + |
| 63 | + vector<int> nums(n, 0); |
| 64 | + cout << "Enter " << n << " elements:" << endl; |
| 65 | + for (int i = 0; i < n; i++) { |
| 66 | + cin >> nums[i]; |
| 67 | + } |
| 68 | + |
| 69 | + cyclicSort(nums); |
| 70 | + print(nums); |
| 71 | + |
| 72 | + return 0; |
| 73 | +} |
0 commit comments