Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit df96740

Browse files
committed
Implemented cocktail shaker sort algorithm
1 parent cedbe13 commit df96740

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

‎Sorts/cocktailShakerSort.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /