Skip to content

Commit 20d63f2

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

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

CPP/basic_programs/cyclic_sort.cpp

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
#include <iostream>
2+
#include <vector>
3+
using namespace std;
4+
5+
void cyclicSort(vector<int>& nums) {
6+
int i = 0;
7+
int n = nums.size();
8+
while (i < n) {
9+
int correctIndex = nums[i] - 1;
10+
if (nums[i] >= 1 && nums[i] <= n && nums[i] != nums[correctIndex]) {
11+
swap(nums[i], nums[correctIndex]);
12+
} else {
13+
i++;
14+
}
15+
}
16+
}
17+
18+
void print(vector<int>& nums){
19+
cout<<"Sorted array is:"<<endl;
20+
21+
for(auto i:nums){
22+
cout<<i<<" "<<endl;
23+
}
24+
}
25+
int main() {
26+
cout<<"This is cyclic sort code. Cyclic sort works from 1 to n or 0 to n-1 without duplicates."<<endl;
27+
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];
33+
cyclicSort(nums);
34+
print(nums);
35+
return 0;
36+
}

0 commit comments

Comments
 (0)