Skip to content

Commit d2f3863

Browse files
authored
Merge pull request larissalages#261 from mulirow/add-cycle-sort
Added cyclesort.cpp
2 parents aa20920 + b21d624 commit d2f3863

File tree

2 files changed

+73
-1
lines changed

2 files changed

+73
-1
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: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ Code | Test
5252
[0/1 Knapsack Problem](https://github.com/ErR0rpj/code_problems/blob/master/classical_algorithms/c%2B%2B/01_knapsack_problem.cpp) | Missing tests
5353
[Kadane's Algorithm](https://github.com/ErR0rpj/code_problems/blob/master/classical_algorithms/c%2B%2B/Kadane_Algorithm.cpp) | Missing tests
5454
[Topological Sort](https://github.com/ErR0rpj/code_problems/blob/master/classical_algorithms/c%2B%2B/Topological_sort.cpp) | Missing Tests
55-
[Bucket Sort](https://github.com/larissalages/code_problems/blob/master/classical_algorithms/c%2B%2B/bucketsort.cpp) | Missing tests
55+
[Cycle Sort](https://github.com/larissalages/code_problems/blob/master/classical_algorithms/c%2B%2B/cyclesort.cpp) | Missing tests
5656
[Bogo Sort](https://github.com/larissalages/code_problems/blob/master/classical_algorithms/c%2B%2B/bogosort.cpp) | Missing tests
5757

5858
# Codeforces

0 commit comments

Comments
 (0)