Cocktail sort
Cocktail sort, also known as bidirectional bubble sort, cocktail shaker sort, shaker sort (which can also refer to a variant of selection sort), ripple sort, shuttle sort or happy hour sort, is a variation of bubble sort that is both a stable sorting algorithm and a comparison sort. The algorithm differs from bubble sort in that sorts in both directions each pass through the list.
Pseudocode
Cocktail sort in pseudocode inspired by the C programming language that sorts a list in increasing order:
function cocktail_sort(list, list_length) // the first element of list has index 0 { bottom = 0; top = list_length - 1; swapped = true; while(swapped == true) // if no elements have been swapped, then the list is sorted { swapped = false; for(i = bottom; i < top; i = i + 1) { if(list[i] > list[i + 1]) // test whether the two elements are in the correct order { swap(list[i], list[i + 1]); // let the two elements change places swapped = true; } } // decreases `top` because the element with the largest value in the unsorted // part of the list is now on the position top top = top - 1; for(i = top; i > bottom; i = i - 1) { if(list[i] < list[i - 1]) { swap(list[i], list[i - 1]); swapped = true; } } // increases `bottom` because the element with the smallest value in the unsorted // part of the list is now on the position bottom bottom = bottom + 1; } }
Optimization
One possible optimization would be to add an if-statement that checks whether there has been a swap after the first pass each iteration. If there hasn't been a swap the list is sorted and the algorithm can stop.
Differences from bubble sort
Cocktail sort is a slight variation of bubble sort. It differs in that instead of repeatedly passing through the list from bottom to top, it passes alternately from bottom to top and then from top to bottom. It can achieve slightly better performance than a standard bubble sort. The reason for this is that bubble sort only passes through the list in one direction and therefore can only move items backward one step each iteration.
An example of a list that proves this point is the list (2,3,4,5,1), which would only need to go through one pass of cocktail sort to become sorted, but if using an ascending bubble sort would take four passes.
Complexity
The complexity of cocktail sort in big O notation is for both the worst case and the average case, but it becomes closer to if the list is mostly ordered at the beginning.