Skip to content

Commit c026857

Browse files
authored
Added cocktail shaker algorithm in c++
1 parent 7d29522 commit c026857

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

CocktailShaker.cpp

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#include <iostream>
2+
#include <vector>
3+
using namespace std;
4+
5+
void cocktailShakerSort(vector<int>& arr) {
6+
bool exchanged = true;
7+
int start = 0;
8+
int end = arr.size() - 1;
9+
10+
while (exchanged) {
11+
exchanged = false;
12+
13+
// Traverse from left to right
14+
for (int i = start; i < end; ++i) {
15+
if (arr[i] > arr[i + 1]) {
16+
swap(arr[i], arr[i + 1]);
17+
exchanged = true;
18+
}
19+
}
20+
21+
// If no elements were swapped, the array is already sorted
22+
if (!exchanged) {
23+
break;
24+
}
25+
26+
exchanged = false;
27+
28+
// Move the end point back by one
29+
--end;
30+
31+
// Traverse from right to left
32+
for (int i = end - 1; i >= start; --i) {
33+
if (arr[i] > arr[i + 1]) {
34+
swap(arr[i], arr[i + 1]);
35+
exchanged = true;
36+
}
37+
}
38+
39+
// Move the start point forward by one
40+
++start;
41+
}
42+
}
43+
44+
int main() {
45+
vector<int> arr = {5, 1, 4, 2, 8, 0, 2, 7};
46+
47+
cocktailShakerSort(arr);
48+
49+
cout << "Sorted array: ";
50+
for (int i : arr) {
51+
cout << i << " ";
52+
}
53+
54+
return 0;
55+
}

0 commit comments

Comments
 (0)