Skip to content

Commit 0038827

Browse files
authored
cycleSort.cpp
code of cycle sort .
1 parent 1443aaa commit 0038827

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Diff for: cycleSort.cpp

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

0 commit comments

Comments
 (0)