Skip to content

Commit e7c6ee6

Browse files
KartikayKartikay
authored andcommitted
Added cyclic sort
1 parent 20d63f2 commit e7c6ee6

File tree

1 file changed

+50
-13
lines changed

1 file changed

+50
-13
lines changed

CPP/basic_programs/cyclic_sort.cpp

Lines changed: 50 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,35 +2,72 @@
22
#include <vector>
33
using namespace std;
44

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
530
void cyclicSort(vector<int>& nums) {
631
int i = 0;
732
int n = nums.size();
833
while (i < n) {
9-
int correctIndex = nums[i] - 1;
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
1037
if (nums[i] >= 1 && nums[i] <= n && nums[i] != nums[correctIndex]) {
1138
swap(nums[i], nums[correctIndex]);
1239
} else {
13-
i++;
40+
i++; // move to next index if already in correct position
1441
}
1542
}
1643
}
1744

18-
void print(vector<int>& nums){
19-
cout<<"Sorted array is:"<<endl;
20-
21-
for(auto i:nums){
22-
cout<<i<<" "<<endl;
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 << " ";
2350
}
51+
cout << endl;
2452
}
53+
54+
// Driver function
2555
int main() {
26-
cout<<"This is cyclic sort code. Cyclic sort works from 1 to n or 0 to n-1 without duplicates."<<endl;
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+
2759
int n;
28-
cout<<"Enter value of n"<<endl;
29-
cin>>n;
30-
vector<int> nums(n,0);
31-
for(int i=0;i<n;i++)
32-
cin>>nums[i];
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+
3369
cyclicSort(nums);
3470
print(nums);
71+
3572
return 0;
3673
}

0 commit comments

Comments
 (0)