forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCocktailShakerSort.java
More file actions
70 lines (56 loc) · 1.37 KB
/
CocktailShakerSort.java
File metadata and controls
70 lines (56 loc) · 1.37 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
package sort;
import static sort.SortUtils.*;
/**
*
* @author Mateus Bizzo (https://github.com/MattBizzo)
* @author Podshivalov Nikita (https://github.com/nikitap492)
*
*/
class CocktailShakerSort implements SortAlgorithm {
/**
* This method implements the Generic Cocktail Shaker Sort
*
* @param array The array to be sorted
* Sorts the array in increasing order
**/
@Override
public <T extends Comparable<T>> T[] sort(T[] array){
int last = array.length;
// Sorting
boolean swap;
do {
swap = false;
//front
for (int count = 0; count <= last - 2; count++) {
if (less(array[count + 1], array[count])) {
swap = swap(array, count, count + 1);
}
}
//break if no swap occurred
if (!swap) {
break;
}
swap = false;
//back
for (int count = last - 2; count >= 0; count--) {
if (less(array[count + 1], array[count])) {
swap = swap(array, count, count + 1);
}
}
last--;
//end
} while (swap);
return array;
}
// Driver Program
public static void main(String[] args) {
// Integer Input
Integer[] integers = { 4, 23, 6, 78, 1, 54, 231, 9, 12 };
CocktailShakerSort shakerSort = new CocktailShakerSort();
// Output => 1 4 6 9 12 23 54 78 231
print(shakerSort.sort(integers));
// String Input
String[] strings = { "c", "a", "e", "b", "d" };
print(shakerSort.sort(strings));
}
}