Skip to content

Commit 810fdd6

Browse files
authored
Merge pull request TheAlgorithms#258 from MattBizzo/master
Adding cocktail shaker sort @MattBizzo Thanks for the PR
2 parents 9d81934 + 952acca commit 810fdd6

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed

Sorts/CocktailShakerSort.java

+86
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
2+
/**
3+
*
4+
* @author Mateus Bizzo (https://github.com/MattBizzo)
5+
*
6+
*/
7+
8+
class CocktailShakerSort {
9+
/**
10+
* This method implements the Generic Cocktail Shaker Sort
11+
*
12+
* @param array
13+
* The array to be sorted
14+
* @param last
15+
* The count of total number of elements in array Sorts the array in
16+
* increasing order
17+
**/
18+
19+
public static <T extends Comparable<T>> void CS(T array[], int last) {
20+
21+
// Sorting
22+
boolean swap;
23+
do {
24+
swap = false;
25+
26+
//front
27+
for (int count = 0; count <= last - 2; count++) {
28+
int comp = array[count].compareTo(array[count + 1]);
29+
if (comp > 0) {
30+
T aux = array[count];
31+
array[count] = array[count + 1];
32+
array[count + 1] = aux;
33+
swap = true;
34+
}
35+
}
36+
//break if no swap occurred
37+
if (!swap) {
38+
break;
39+
}
40+
swap = false;
41+
42+
//back
43+
for (int count = last - 2; count >= 0; count--) {
44+
int comp = array[count].compareTo(array[count + 1]);
45+
if (comp > 0) {
46+
T aux = array[count];
47+
array[count] = array[count + 1];
48+
array[count + 1] = aux;
49+
swap = true;
50+
}
51+
}
52+
last--;
53+
//end
54+
} while (swap);
55+
}
56+
57+
// Driver Program
58+
public static void main(String[] args) {
59+
// Integer Input
60+
int[] arr1 = { 4, 23, 6, 78, 1, 54, 231, 9, 12 };
61+
int last = arr1.length;
62+
Integer[] array = new Integer[last];
63+
for (int i = 0; i < last; i++) {
64+
array[i] = arr1[i];
65+
}
66+
67+
CS(array, last);
68+
69+
// Output => 1 4 6 9 12 23 54 78 231
70+
for (int i = 0; i < last; i++) {
71+
System.out.print(array[i] + "\t");
72+
}
73+
System.out.println();
74+
75+
// String Input
76+
String[] array1 = { "c", "a", "e", "b", "d" };
77+
last = array1.length;
78+
79+
CS(array1, last);
80+
81+
// Output => a b c d e
82+
for (int i = 0; i < last; i++) {
83+
System.out.print(array1[i] + "\t");
84+
}
85+
}
86+
}

0 commit comments

Comments
 (0)