#include <stdio.h>
void swap(int xp, int yp) {
int temp = *xp;
xp = yp;
*yp = temp;
}
void cocktailSort(int arr[], int n) {
int swapped = 1;
int start = 0;
int end = n - 1;
while (swapped) {
// Initialize swapped as false so that the loop runs only if there is a swap
swapped = 0;
// Forward bubble sort
for (int i = start; i < end; ++i) {
if (arr[i] > arr[i + 1]) {
swap(&arr[i], &arr[i + 1]);
swapped = 1;
}
}
// If no two elements were swapped, the array is sorted
if (!swapped)
break;
// Reduce the end pointer because the largest element is in its sorted position
--end;
// Initialize swapped as false for the following backward loop
swapped = 0;
// Backward bubble sort
for (int i = end - 1; i >= start; --i) {
if (arr[i] > arr[i + 1]) {
swap(&arr[i], &arr[i + 1]);
swapped = 1;
}
}
// Increase the start pointer because the smallest element is in its sorted position
++start;
}
}
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
cocktailSort(arr, n);
printf("Sorted array: \n");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}