-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathshaker-sort.js
41 lines (36 loc) · 876 Bytes
/
shaker-sort.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
41
/**
* Swaps two values in an array.
* @param {Array} items The array containing the items.
* @param {int} firstIndex Index of first item to swap.
* @param {int} secondIndex Index of second item to swap.
* @return {void}
*/
function swap(items, firstIndex, secondIndex){
var temp = items[firstIndex];
items[firstIndex] = items[secondIndex];
items[secondIndex] = temp;
}
/**
* A shaker sort implementation in JavaScript.
* @param {Array} items An array of items to sort.
* @return {Array} The sorted array.
*/
function shakerSort(items) {
var start = 0,
end = items.length - 1,
i;
do {
for (i = end; i > 0; i--) {
if (items[i-1] >= items[i]) {
swap(items, i, i-1);
start = i + 1;
}
}
for (i = 1; i <= start; i++) {
if (items[i-1] > items[i]) {
swap(items, i, i-1);
end = i - 1;
}
}
} while (start < end);
}