Skip to content

Commit 5e30a6d

Browse files
authored
Merge pull request #24 from CSESandeepan39/main
Added cycle sort algorithm in C++
2 parents 8128dfc + fa9eaee commit 5e30a6d

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Cycle_sort.cpp

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#include<iostream>
2+
using namespace std;
3+
void cycleSort(int a[], int n) {
4+
int writes = 0;
5+
for (int c_start = 0; c_start <= n - 2; c_start++) {
6+
int item = a[c_start];
7+
int pos = c_start;
8+
for (int i = c_start + 1; i < n; i++)
9+
if (a[i] < item)
10+
pos++;
11+
if (pos == c_start)
12+
continue;
13+
while (item == a[pos])
14+
pos += 1;
15+
if (pos != c_start) {
16+
swap(item, a[pos]);
17+
writes++;
18+
}
19+
while (pos != c_start) {
20+
pos = c_start;
21+
for (int i = c_start + 1; i < n; i++)
22+
if (a[i] < item)
23+
pos += 1;
24+
while (item == a[pos])
25+
pos += 1;
26+
if (item != a[pos]) {
27+
swap(item, a[pos]);
28+
writes++;
29+
}
30+
}
31+
}
32+
}
33+
int main() {
34+
int a[] ={7,4,3,5,2,1,6};
35+
int n = 7;
36+
cycleSort(a, n);
37+
for (int i = 0; i < n; i++)
38+
cout << a[i] << " ";
39+
return 0;
40+
}

0 commit comments

Comments
 (0)