-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCocktailSort.java
More file actions
81 lines (50 loc) · 1.85 KB
/
CocktailSort.java
File metadata and controls
81 lines (50 loc) · 1.85 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
import java.util.Arrays;
public class CocktailSort {
String complexity;
CocktailSort() {
complexity = ". Quadratic Time Complexity.";
}
void sort(int[] sortArray) {
/*
Begin Time Start
*/
double start = (double) System.nanoTime();
boolean swap = true;
int first = 0;
int last = sortArray.length;
while (swap) {
swap = false;
for (int count = first; count < last - 1; count++) {
if (sortArray[count] > sortArray[count + 1]) {
int tempInt = sortArray[count];
sortArray[count] = sortArray[count + 1];
sortArray[count + 1] = tempInt;
swap = true;
}
}
if (!swap) {
// Break out of the loop
break;
}
// Reset swap for next for, and last place item is correct so move position
swap = false;
last--;
for (int count = last - 1; count >= first; count--) {
if (sortArray[count] > sortArray[count + 1]) {
int tempInt = sortArray[count];
sortArray[count] = sortArray[count + 1];
sortArray[count + 1] = tempInt;
// can't have outside loop or the entire while would end
swap = true;
}
}
// first place is correct, so move position
start++;
}
/*
End Time
*/
double end = (double) System.nanoTime();
System.out.println("CocktailSort: " + Arrays.toString(sortArray) + complexity + " Seconds taken was " + ((end - start) / 1000000));
}
}