diff --git a/src/cpp/CocktailShaker.cpp b/src/cpp/CocktailShaker.cpp new file mode 100644 index 00000000..e5dd51ec --- /dev/null +++ b/src/cpp/CocktailShaker.cpp @@ -0,0 +1,55 @@ +#include +#include +using namespace std; + +void cocktailShakerSort(vector& 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 arr = {5, 1, 4, 2, 8, 0, 2, 7}; + + cocktailShakerSort(arr); + + cout << "Sorted array: "; + for (int i : arr) { + cout << i << " "; + } + + return 0; +}