Sorts array a[0..n-1] using Cocktail sort
| 4 | |
| 5 | // Sorts array a[0..n-1] using Cocktail sort |
| 6 | void CocktailSort(int a[], int n) |
| 7 | { |
| 8 | bool swapped = true; |
| 9 | int start = 0; |
| 10 | int end = n - 1; |
| 11 | |
| 12 | while (swapped) { |
| 13 | // reset the swapped flag on entering |
| 14 | // the loop, because it might be true from |
| 15 | // a previous iteration. |
| 16 | swapped = false; |
| 17 | |
| 18 | // loop from left to right same as |
| 19 | // the bubble sort |
| 20 | for (int i = start; i < end; ++i) { |
| 21 | if (a[i] > a[i + 1]) { |
| 22 | swap(a[i], a[i + 1]); |
| 23 | swapped = true; |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | // if nothing moved, then array is sorted. |
| 28 | if (!swapped) |
| 29 | break; |
| 30 | |
| 31 | // otherwise, reset the swapped flag so that it |
| 32 | // can be used in the next stage |
| 33 | swapped = false; |
| 34 | |
| 35 | // move the end point back by one, because |
| 36 | // item at the end is in its rightful spot |
| 37 | --end; |
| 38 | |
| 39 | // from right to left, doing the |
| 40 | // same comparison as in the previous stage |
| 41 | for (int i = end - 1; i >= start; --i) { |
| 42 | if (a[i] > a[i + 1]) { |
| 43 | swap(a[i], a[i + 1]); |
| 44 | swapped = true; |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | // increase the starting point, because |
| 49 | // the last stage would have moved the next |
| 50 | // smallest number to its rightful spot. |
| 51 | ++start; |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | /* Prints the array */ |
| 56 | void printArray(int a[], int n) |