forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCocktailShakerSort.js
More file actions
Latest commit
31 lines (28 loc) · 924 Bytes
/
Copy pathCocktailShakerSort.js
File metadata and controls
31 lines (28 loc) · 924 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* 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
*/
exportfunctioncocktailShakerSort(items){
for(leti=items.length-1;i>0;i--){
letj
// 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]]
}
}
// Forwards
for(j=0;j<i;j++){
if(items[j]>items[j+1]){
[items[j],items[j+1]]=[items[j+1],items[j]]
}
}
}
returnitems
}