class CocktailSort
{
/**
* Performs a bi-directional bubble sort on the passed set, also know as a cocktail sort.
* After making passes from left to right, the algorithm then passes from right to left
*/
int beg = 0; //Beginning index for the left-to-right pass
int end = unsorted.length - 1; //End index for the left-to-right pass
Integer tmp =
null;
//Temporary variable for swapping
boolean hasSwapped; //Denotes whether a swap was made during a pass
do {
hasSwapped = false;
//Bubble sort from left-to-right starting at beg and ending at end
for (int i = beg;i < end;++i) {
if (unsorted[i] > unsorted[i + 1]) {
tmp = unsorted[i];
unsorted[i] = unsorted[i + 1];
unsorted[i + 1] = tmp;
hasSwapped = true;
}
}
end--; //Decrease end by one
//Bubble sort from right-to-left starting at end and ending at beg
for (int i = end;i > beg;--i) {
if (unsorted[i] < unsorted[i - 1]) {
tmp = unsorted[i];
unsorted[i] = unsorted[i - 1];
unsorted[i - 1] = tmp;
hasSwapped = true;
}
}
beg++; //Increment beg by one
} while ((hasSwapped == true) && (beg != end)); //While no swaps have been made
return unsorted;
}
/**
* Invokes a cocktail sort on the unsorted unsorted
* @param unsorted the unsorted integer set to be sorted
* @return a sorted version of the unsorted integer set
*/
return cocktailSort(unsorted.clone());
}
}