forked from TheAlgorithms/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCocktailShakerSort.js
40 lines (36 loc) · 941 Bytes
/
CocktailShakerSort.js
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
32
33
34
35
36
37
38
39
40
/*
* 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 (let i = items.length - 1; i > 0; i--) {
let swapped = false
let j
// 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
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
var ar = [5, 6, 7, 8, 1, 2, 12, 14]
// Array before Sort
console.log(ar)
cocktailShakerSort(ar)
// Array after sort
console.log(ar)