public class CocktailSort {
void printArray(int a[])
{
int n = a.length;
for (int i = 0; i < n; i++)
System.out.print(a[i] + " ");
System.out.println();
}
// Driver code
public static void main(String[] args)
{
CocktailSort ob = new CocktailSort();
int a[] = { 5, 1, 4, 2, 8, 0, 2 };
cocktailSort(a);
System.out.println("Sorted array");
ob.printArray(a);
}
public static void cocktailSort(int [] arr){
int temp = arr[0];
boolean swapped = true;
int start=0, end = arr.length-1;
int itr=0;
while(swapped){
swapped = false;
for(int i=start;i<end;i++){
if(arr[i]>arr[i+1]){
temp = arr[i];
arr[i] =arr[i+1];
arr[i+1]=temp;
swapped = true;
}
}
end--;
for(int i=end;i>start;i--){
if(arr[i]<arr[i-1]){
temp = arr[i];
arr[i] =arr[i-1];
arr[i-1]=temp;
swapped = true;
}
}
start++;
itr++;
}
System.out.println("itr::"+itr);
}
}
Output :
itr::3 Sorted array 0 1 2 2 4 5 8