Skip to content

Commit 4c408f1

Browse files
committed
Added cycle sort
1 parent 07e254f commit 4c408f1

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
// Cycle sort is an optimal sorting algorithm regarding the number of memory memWrite to sort.
6+
7+
// Algorithm:
8+
void cycleSort(int array[], int n){
9+
int memWrite = 0;
10+
11+
for(int cycle = 0; cycle <= n - 2; cycle++){
12+
int start = array[cycle];
13+
int pos = cycle;
14+
15+
for(int i = (cycle + 1); i < n; i++){
16+
if (array[i] < start){
17+
pos++;
18+
}
19+
}
20+
21+
if (pos == cycle){
22+
continue;
23+
}
24+
25+
while (start == array[pos]){
26+
pos += 1;
27+
}
28+
29+
if (pos != cycle){
30+
swap(start, array[pos]);
31+
memWrite++;
32+
}
33+
34+
while(pos != cycle){
35+
pos = cycle;
36+
37+
for(int i = cycle + 1; i < n; i++){
38+
if (array[i] < start){
39+
pos += 1;
40+
}
41+
}
42+
43+
while(start == array[pos]){
44+
pos += 1;
45+
}
46+
47+
if(start != array[pos]){
48+
swap(start, array[pos]);
49+
memWrite++;
50+
}
51+
}
52+
}
53+
}
54+
55+
// Test:
56+
int main(){
57+
int array[] = {5, 1, 9, 2, 91, 23, 519, 43, 19, 3, 4, 3, 10};
58+
int n = sizeof(array) / sizeof(array[0]);
59+
cout << "Elements before cycle sort:\n";
60+
for (int i = 0; i < n; i++){
61+
cout << array[i] << " ";
62+
}
63+
cout << "\n";
64+
65+
cycleSort(array, n);
66+
67+
cout << "Elements after cycle sort:\n";
68+
for (int i = 0; i < n; i++){
69+
cout << array[i] << " ";
70+
}
71+
cout << "\n";
72+
}

readme.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ Code | Test
4949
[0/1 Knapsack Problem](https://github.com/ErR0rpj/code_problems/blob/master/classical_algorithms/c%2B%2B/01_knapsack_problem.cpp) | Missing tests
5050
[Kadane's Algorithm](https://github.com/ErR0rpj/code_problems/blob/master/classical_algorithms/c%2B%2B/Kadane_Algorithm.cpp) | Missing tests
5151
[Topological Sort](https://github.com/ErR0rpj/code_problems/blob/master/classical_algorithms/c%2B%2B/Topological_sort.cpp) | Missing Tests
52+
[Cycle Sort](https://github.com/larissalages/code_problems/blob/master/classical_algorithms/c%2B%2B/cyclesort.cpp) | Missing tests
53+
5254

5355
# Codeforces
5456

0 commit comments

Comments
 (0)