-
Notifications
You must be signed in to change notification settings - Fork 271
/
Copy pathCocktailShaker.cpp
55 lines (43 loc) · 1.19 KB
/
CocktailShaker.cpp
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <vector>
using namespace std;
void cocktailShakerSort(vector<int>& arr) {
bool exchanged = true;
int start = 0;
int end = arr.size() - 1;
while (exchanged) {
exchanged = false;
// Traverse from left to right
for (int i = start; i < end; ++i) {
if (arr[i] > arr[i + 1]) {
swap(arr[i], arr[i + 1]);
exchanged = true;
}
}
// If no elements were swapped, the array is already sorted
if (!exchanged) {
break;
}
exchanged = false;
// Move the end point back by one
--end;
// Traverse from right to left
for (int i = end - 1; i >= start; --i) {
if (arr[i] > arr[i + 1]) {
swap(arr[i], arr[i + 1]);
exchanged = true;
}
}
// Move the start point forward by one
++start;
}
}
int main() {
vector<int> arr = {5, 1, 4, 2, 8, 0, 2, 7};
cocktailShakerSort(arr);
cout << "Sorted array: ";
for (int i : arr) {
cout << i << " ";
}
return 0;
}