Skip to content

Commit 8e3b6a2

Browse files
authored
Merge pull request deutranium#214 from gabrielhs1357/cocktailSort
implemented cocktail sorting using javascript
2 parents dd404a5 + 394f170 commit 8e3b6a2

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
function cocktailSort(array) {
2+
3+
var n = array.length;
4+
5+
var isSorted = false;
6+
7+
while (!isSorted) {
8+
isSorted = true;
9+
10+
for (var i = 0; i < n - 1; i++) {
11+
if (array[i] > array[i + 1]) {
12+
var temp = array[i];
13+
array[i] = array[i + 1];
14+
array[i + 1] = temp;
15+
isSorted = false;
16+
}
17+
}
18+
19+
if (isSorted) {
20+
break;
21+
}
22+
23+
isSorted = true;
24+
25+
for (var j = n - 1; j > 0; j--) {
26+
if (array[j - 1] > array[j]) {
27+
var temp = array[j];
28+
array[j] = array[j + 1];
29+
array[j + 1] = temp;
30+
isSorted = false;
31+
}
32+
}
33+
}
34+
35+
return array;
36+
}

0 commit comments

Comments
 (0)