|
1 | 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 |
| 2 | + * Cocktail Shaker Sort is an algorithm that is a Bidirectional Bubble Sort. |
| 3 | + * The algorithm extends bubble sort by operating in two directions. |
| 4 | + * While it improves on bubble sort by more quickly moving items to the beginning of the list, |
| 5 | + * it provides only marginal performance improvements. |
5 | 6 | *
|
| 7 | + * Wikipedia (Cocktail Shaker Sort): https://en.wikipedia.org/wiki/Cocktail_shaker_sort |
| 8 | + * Wikipedia (Bubble Sort): https://en.wikipedia.org/wiki/Bubble_sort |
| 9 | + * |
| 10 | + */ |
| 11 | + |
| 12 | +/** |
| 13 | + * Doctests |
| 14 | + * |
| 15 | + * > cocktailShakerSort([5, 4, 1, 2, 3]) |
| 16 | + * [1, 2, 3, 4, 5] |
| 17 | + * > cocktailShakerSort([]) |
| 18 | + * [] |
| 19 | + * > cocktailShakerSort([1, 2, 3]) |
| 20 | + * [1, 2, 3] |
6 | 21 | */
|
| 22 | + |
7 | 23 | function cocktailShakerSort (items) {
|
8 | 24 | for (let i = items.length - 1; i > 0; i--) {
|
9 |
| - let swapped = false |
10 | 25 | let j
|
11 | 26 |
|
12 |
| - // backwards |
| 27 | + // Backwards |
13 | 28 | for (j = items.length - 1; j > i; j--) {
|
14 | 29 | if (items[j] < items[j - 1]) {
|
15 | 30 | [items[j], items[j - 1]] = [items[j - 1], items[j]]
|
16 |
| - swapped = true |
17 | 31 | }
|
18 | 32 | }
|
19 | 33 |
|
20 |
| - // forwards |
| 34 | + // Forwards |
21 | 35 | for (j = 0; j < i; j++) {
|
22 | 36 | if (items[j] > items[j + 1]) {
|
23 | 37 | [items[j], items[j + 1]] = [items[j + 1], items[j]]
|
24 |
| - swapped = true |
25 | 38 | }
|
26 | 39 | }
|
27 |
| - if (!swapped) { |
28 |
| - return |
29 |
| - } |
30 | 40 | }
|
31 |
| -} |
32 | 41 |
|
33 |
| -// Implementation of cocktailShakerSort |
| 42 | + return items |
| 43 | +} |
34 | 44 |
|
35 |
| -var ar = [5, 6, 7, 8, 1, 2, 12, 14] |
36 |
| -// Array before Sort |
37 |
| -console.log(ar) |
38 |
| -cocktailShakerSort(ar) |
39 |
| -// Array after sort |
40 |
| -console.log(ar) |
| 45 | +/** |
| 46 | +* Implementation of Cocktail Shaker Sort |
| 47 | +*/ |
| 48 | +const array = [5, 6, 7, 8, 1, 2, 12, 14] |
| 49 | +// Before Sort |
| 50 | +console.log('\n- Before Sort | Implementation of Cocktail Shaker Sort -') |
| 51 | +console.log(array) |
| 52 | +// After Sort |
| 53 | +console.log('- After Sort | Implementation of Cocktail Shaker Sort -') |
| 54 | +console.log(cocktailShakerSort(array)) |
| 55 | +console.log('\n') |
0 commit comments