Skip to content

Commit 1abd3aa

Browse files
authored
Merge pull request #545 from marsonya/doctests/cocktail-shaker-sort
Improved CocktailShakerSort and added Doctests
2 parents 74f9bfb + d44ffef commit 1abd3aa

File tree

1 file changed

+34
-19
lines changed

1 file changed

+34
-19
lines changed

Sorts/CocktailShakerSort.js

Lines changed: 34 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,55 @@
11
/*
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.
56
*
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]
621
*/
22+
723
function cocktailShakerSort (items) {
824
for (let i = items.length - 1; i > 0; i--) {
9-
let swapped = false
1025
let j
1126

12-
// backwards
27+
// Backwards
1328
for (j = items.length - 1; j > i; j--) {
1429
if (items[j] < items[j - 1]) {
1530
[items[j], items[j - 1]] = [items[j - 1], items[j]]
16-
swapped = true
1731
}
1832
}
1933

20-
// forwards
34+
// Forwards
2135
for (j = 0; j < i; j++) {
2236
if (items[j] > items[j + 1]) {
2337
[items[j], items[j + 1]] = [items[j + 1], items[j]]
24-
swapped = true
2538
}
2639
}
27-
if (!swapped) {
28-
return
29-
}
3040
}
31-
}
3241

33-
// Implementation of cocktailShakerSort
42+
return items
43+
}
3444

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

Comments
 (0)