-
Notifications
You must be signed in to change notification settings - Fork 167
Expand file tree
/
Copy pathCocktailSort.js
More file actions
31 lines (31 loc) · 814 Bytes
/
CocktailSort.js
File metadata and controls
31 lines (31 loc) · 814 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
const cocktailSort = (arrInput) => {
let startIndex = 0, endIndex = arrInput.length, isSwapped = true;
while (isSwapped) {
isSwapped = false;
for (let i = startIndex; i < endIndex - 1; i++) {
if (arrInput[i] > arrInput[i + 1]) {
let temp = arrInput[i];
arrInput[i] = arrInput[i + 1];
arrInput[i + 1] = temp;
isSwapped = true;
}
}
endIndex--;
if (!isSwapped) break;
isSwapped = false;
for (let i = endIndex - 1; i > startIndex; i--) {
if (arrInput[i - 1] > arrInput[i]) {
let temp = arrInput[i];
arrInput[i] = arrInput[i - 1];
arrInput[i - 1] = temp;
isSwapped = true;
}
}
startIndex++;
}
return arrInput;
}
//Cocktail Sort is a variatio of bubble sort.
//Example Usage :
// let myArr = [8, 6, -4, 1, 84, 35]
// console.log(cocktailSort(myArr))