|
| 1 | +// Java program for implementation of Cocktail Sort |
| 2 | +public class CocktailSort |
| 3 | +{ |
| 4 | + void cocktailSort(int a[]) |
| 5 | + { |
| 6 | + boolean swapped = true; |
| 7 | + int start = 0; |
| 8 | + int end = a.length; |
| 9 | + |
| 10 | + while (swapped == true) |
| 11 | + { |
| 12 | + // reset the swapped flag on entering the |
| 13 | + // loop, because it might be true from a |
| 14 | + // previous iteration. |
| 15 | + swapped = false; |
| 16 | + |
| 17 | + // loop from bottom to top same as |
| 18 | + // the bubble sort. |
| 19 | + for (int i = start; i < end - 1; ++i) |
| 20 | + { |
| 21 | + if (a[i] > a[i + 1]) { |
| 22 | + int temp = a[i]; |
| 23 | + a[i] = a[i + 1]; |
| 24 | + a[i + 1] = temp; |
| 25 | + swapped = true; |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + // if nothing moved, then array is sorted. |
| 30 | + if (swapped == false) |
| 31 | + break; |
| 32 | + |
| 33 | + // otherwise, reset the swapped flag so that it |
| 34 | + // can be used in the next stage |
| 35 | + swapped = false; |
| 36 | + |
| 37 | + // move the end point back by one, because |
| 38 | + // item at the end is in its rightful spot |
| 39 | + end = end - 1; |
| 40 | + |
| 41 | + // from top to bottom, doing the |
| 42 | + // same comparison as in the previous stage |
| 43 | + for (int i = end - 1; i >= start; i--) |
| 44 | + { |
| 45 | + if (a[i] > a[i + 1]) |
| 46 | + { |
| 47 | + int temp = a[i]; |
| 48 | + a[i] = a[i + 1]; |
| 49 | + a[i + 1] = temp; |
| 50 | + swapped = true; |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + // increase the starting point, because |
| 55 | + // the last stage would have moved the next |
| 56 | + // smallest number to its rightful spot. |
| 57 | + start = start + 1; |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + /* Prints the array */ |
| 62 | + void printArray(int a[]) |
| 63 | + { |
| 64 | + int n = a.length; |
| 65 | + for (int i = 0; i < n; i++) |
| 66 | + System.out.print(a[i] + " "); |
| 67 | + System.out.println(); |
| 68 | + } |
| 69 | + |
| 70 | + // Driver code |
| 71 | + public static void main(String[] args) |
| 72 | + { |
| 73 | + CocktailSort ob = new CocktailSort(); |
| 74 | + int a[] = { 5, 1, 4, 2, 8, 0, 2 }; |
| 75 | + ob.cocktailSort(a); |
| 76 | + System.out.println("Sorted array"); |
| 77 | + ob.printArray(a); |
| 78 | + } |
| 79 | +} |
0 commit comments