1
+ /*
2
+ * Cocktail shaker sort is a sort algorithm that is a bidirectional bubble sort
3
+ * more information: https://en.wikipedia.org/wiki/Cocktail_shaker_sort
4
+ * more information: https://en.wikipedia.org/wiki/Bubble_sort
5
+ *
6
+ */
7
+ function cocktailShakerSort ( items ) {
8
+
9
+ for ( var i = items . length - 1 ; i > 0 ; i -- ) {
10
+ var swapped = false ;
11
+ var temp , j ;
12
+
13
+ // backwards
14
+ for ( j = 0 ; j > i ; j -- ) {
15
+ if ( items [ j ] < items [ j - 1 ] ) {
16
+ temp = items [ j ] ;
17
+ items [ j ] = items [ j - 1 ] ;
18
+ items [ j - 1 ] = temp ;
19
+ swapped = true ;
20
+ }
21
+ }
22
+
23
+ //forwards
24
+ for ( j = 0 ; j < i ; j ++ ) {
25
+ if ( items [ j ] > items [ j + 1 ] ) {
26
+ temp = items [ j ] ;
27
+ items [ j ] = items [ j + 1 ] ;
28
+ items [ j + 1 ] = temp ;
29
+ swapped = true ;
30
+ }
31
+ }
32
+ if ( ! swapped ) {
33
+ return ;
34
+ }
35
+ }
36
+ }
37
+
38
+ //Implementation of cocktailShakerSort
39
+
40
+ var ar = [ 5 , 6 , 7 , 8 , 1 , 2 , 12 , 14 ] ;
41
+ //Array before Sort
42
+ console . log ( ar ) ;
43
+ cocktailShakerSort ( ar ) ;
44
+ //Array after sort
45
+ console . log ( ar ) ;
0 commit comments