We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 48046c3 commit 20d63f2Copy full SHA for 20d63f2
1 file changed
CPP/basic_programs/cyclic_sort.cpp
@@ -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