Java Program for Cocktail Sort


Cocktail Sort works in contrast to bubble sort, wherein elements are iterated from left to right, and the largest element is first brought to its correct position and so on. In cocktail sort, elements are iterated over in both the directions (left and right) in an alternating fashion.

Following is the program for Cocktail Sort −

Example

 Live Demo

public class Demo{
   static int temp;
   static void Cocktail(int a[], int n){
      boolean swap = true;
      int begin = 0,i;
      int end = n - 1;
      while (swap) {
         swap = false;
         for (i = begin; i < end; ++i){
            if (a[i] > a[i + 1]){
               temp = a[i];
               a[i]=a[i+1];
               a[i+1]=temp;
               swap = true;
            }
         }
         if (!swap)
         break;
         swap = false;
         for (i = end - 1; i >= begin; --i){
            if (a[i] > a[i + 1]){
               temp = a[i];
               a[i]=a[i+1];
               a[i+1]=temp;
               swap = true;
            }
         }
         ++begin;
      }
   }
   public static void main(String[] args) {
      int my_arr[] = {34, 78, 90, 32, 67, 12, 1, 0, 95};
      Cocktail(my_arr, my_arr.length);
      System.out.println("The sorted array is ");
      for (int i = 0; i < my_arr.length; i++)
      System.out.print(my_arr[i]+" ");
      System.out.println();
   }
}

Output

The sorted array is
0 1 12 32 34 67 78 90 95

In the first step, the loop is run from left to right (similar to bubble sort) during which, the adjacent items are compared. If the left handed value is greater than the right handed value, the values are swapped. Once the first iteration is over, the largest element will be found at the end of the array. In the next step, the loop is run from right to left, by leaving the most recently sorted item. Here again, the adjacent elements are compared and the greater element is added to the end of the array.

Updated on: 04-Jul-2020

197 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements