Skip to content

Commit 186c5d0

Browse files
author
MattBizzo
committed
Adding cocktail sort
1 parent 531c763 commit 186c5d0

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

Sorts/CocktailShakerSort.java

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

0 commit comments

Comments
 (0)