Skip to content

Implemented cocktail shaker sort algorithm #22

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

Merged
merged 1 commit into from
Oct 7, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions Sorts/cocktailShakerSort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
* 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
*
*/
function cocktailShakerSort(items) {

for (var i = items.length - 1; i > 0; i--) {
var swapped = false;
var temp, j;

// backwards
for (j = 0; j > i; j--) {
if (items[j] < items[j - 1]) {
temp = items[j];
items[j] = items[j - 1];
items[j - 1] = temp;
swapped = true;
}
}

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

//Implementation of cocktailShakerSort

var ar = [5, 6, 7, 8, 1, 2, 12, 14];
//Array before Sort
console.log(ar);
cocktailShakerSort(ar);
//Array after sort
console.log(ar);