-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCycleSort.java
More file actions
102 lines (60 loc) · 2.13 KB
/
CycleSort.java
File metadata and controls
102 lines (60 loc) · 2.13 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import java.util.Arrays;
public class CycleSort {
String complexity;
CycleSort() {
complexity = ". Quadratic Time Complexity.";
}
void sort(int[] sortArray) {
/*
Begin Time Start
*/
double start = (double) System.nanoTime();
int changes = 0;
for (int cycle = 0; cycle <= sortArray.length - 2; cycle++) {
int select = sortArray[cycle];
int position = cycle;
for (int count = cycle + 1; count < sortArray.length; count++) {
if (sortArray[count] < select) {
position++;
}
}
// Check if already correct first
if (position == cycle) {
continue;
}
// Skip homogeneous items
while (select == sortArray[position]) {
position++;
}
if (position != cycle) {
int tempInt = select;
select = sortArray[position];
sortArray[position] = tempInt;
changes++;
}
// Change the cycle
while (position != cycle) {
position = cycle;
for (int count = cycle + 1; count < sortArray.length; count++) {
if (sortArray[count] < select) {
position++;
}
}
while (select == sortArray[position]) {
position++;
}
if (select != sortArray[position]) {
int tempInt = select;
select = sortArray[position];
sortArray[position] = tempInt;
changes++;
}
}
}
/*
End Time
*/
double end = (double) System.nanoTime();
System.out.println("CycleSort: " + Arrays.toString(sortArray) + complexity + " Seconds taken was " + ((end - start) / 1000000));
}
}