Skip to content

Improved CocktailShakerSort and added Doctests #465

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 12 commits into from
54 changes: 34 additions & 20 deletions Sorts/CocktailShakerSort.js
Original file line number Diff line number Diff line change
@@ -1,40 +1,54 @@
/*
* Cocktail shaker sort is a sort algorithm that is a bidirectional bubble sort
* more information: https://en.wikipedia.org/wiki/Cocktail_shaker_sort
* more information: https://en.wikipedia.org/wiki/Bubble_sort
/**
* Cocktail Shaker Sort is an algorithm that is a Bidirectional Bubble Sort.
* The algorithm extends bubble sort by operating in two directions.
* While it improves on bubble sort by more quickly moving items to the beginning of the list,
* it provides only marginal performance improvements.
*
* Wikipedia (Cocktail Shaker Sort): https://en.wikipedia.org/wiki/Cocktail_shaker_sort
* Wikipedia (Bubble Sort): https://en.wikipedia.org/wiki/Bubble_sort
*/

/**
* Doctests
*
* > cocktailShakerSort([5, 4, 1, 2, 3])
* [1, 2, 3, 4, 5]
* > cocktailShakerSort([])
* []
* > cocktailShakerSort([1, 2, 3])
* [1, 2, 3]
*/

function cocktailShakerSort (items) {
for (let i = items.length - 1; i > 0; i--) {
let swapped = false
let j

// backwards
// Backwards
for (j = items.length - 1; j > i; j--) {
if (items[j] < items[j - 1]) {
[items[j], items[j - 1]] = [items[j - 1], items[j]]
swapped = true
}
}

// forwards
// Forwards
for (j = 0; j < i; j++) {
if (items[j] > items[j + 1]) {
[items[j], items[j + 1]] = [items[j + 1], items[j]]
swapped = true
}
}
if (!swapped) {
return
}
}
}

// Implementation of cocktailShakerSort
return items
}

var ar = [5, 6, 7, 8, 1, 2, 12, 14]
// Array before Sort
console.log(ar)
cocktailShakerSort(ar)
// Array after sort
console.log(ar)
/**
* Implementation of Cocktail Shaker Sort
*/
var array = [5, 6, 7, 8, 1, 2, 12, 14]
// Before Sort
console.log('\n- Before Sort | Implementation of Cocktail Shaker Sort -')
console.log(array)
// After Sort
console.log('- After Sort | Implementation of Cocktail Shaker Sort -')
console.log(cocktailShakerSort(array))
console.log('\n')