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