File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments