Recent from talks
Nothing was collected or created yet.
Cocktail shaker sort
View on Wikipedia![]() | |
| Class | Sorting algorithm |
|---|---|
| Data structure | Array |
| Worst-case performance | |
| Best-case performance | |
| Average performance | |
| Worst-case space complexity | |
| Optimal | No |
Cocktail shaker sort,[1] also known as bidirectional bubble sort,[2] cocktail sort, shaker sort (which can also refer to a variant of selection sort), ripple sort, shuffle sort,[3] or shuttle sort, is an extension of bubble sort. The algorithm extends bubble sort by operating in two directions. While it improves on bubble sort by more quickly moving items to the beginning of the list, it provides only marginal performance improvements.
Like most variants of bubble sort, cocktail shaker sort is used primarily as an educational tool. More efficient algorithms such as quicksort, merge sort, or timsort are used by the sorting libraries built into popular programming languages such as Python and Java.[4][5]
Pseudocode
[edit]The simplest form goes through the whole list each time:
procedure cocktailShakerSort(A : list of sortable items) is
do
swapped := false
for each i in 0 to length(A) − 1 do:
if A[i] > A[i + 1] then // test whether the two elements are in the wrong order
swap(A[i], A[i + 1]) // let the two elements change places
swapped := true
end if
end for
if not swapped then
// we can exit the outer loop here if no swaps occurred.
break do-while loop
end if
swapped := false
for each i in length(A) − 1 to 0 do:
if A[i] > A[i + 1] then
swap(A[i], A[i + 1])
swapped := true
end if
end for
while swapped // if no elements have been swapped, then the list is sorted
end procedure
The first rightward pass will shift the largest element to its correct place at the end, and the following leftward pass will shift the smallest element to its correct place at the beginning. The second complete pass will shift the second largest and second smallest elements to their correct places, and so on. After i passes, the first i and the last i elements in the list are in their correct positions, and do not need to be checked. By shortening the part of the list that is sorted each time, the number of operations can be halved (see bubble sort).
This is an example of the algorithm in MATLAB/OCTAVE with the optimization of remembering the last swap index and updating the bounds.
function A = cocktailShakerSort(A)
% `beginIdx` and `endIdx` marks the first and last index to check
beginIdx = 1;
endIdx = length(A) - 1;
while beginIdx <= endIdx
newBeginIdx = endIdx;
newEndIdx = beginIdx;
for ii = beginIdx:endIdx
if A(ii) > A(ii + 1)
[A(ii+1), A(ii)] = deal(A(ii), A(ii+1));
newEndIdx = ii;
end
end
% decreases `endIdx` because the elements after `newEndIdx` are in correct order
endIdx = newEndIdx - 1;
for ii = endIdx:-1:beginIdx
if A(ii) > A(ii + 1)
[A(ii+1), A(ii)] = deal(A(ii), A(ii+1));
newBeginIdx = ii;
end
end
% increases `beginIdx` because the elements before `newBeginIdx` are in correct order
beginIdx = newBeginIdx + 1;
end
end
Differences from bubble sort
[edit]Cocktail shaker sort is a slight variation of bubble sort.[1] 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. However one cocktail sort pass should be counted as two bubble sort passes. Typically cocktail sort is less than two times faster than bubble sort.
Another optimization can be that the algorithm remembers where the last actual swap has been done. In the next iteration, there will be no swaps beyond this limit and the algorithm has shorter passes. As the cocktail shaker sort goes bidirectionally, the range of possible swaps, which is the range to be tested, will reduce per pass, thus reducing the overall running time slightly.
Complexity
[edit]The complexity of the cocktail shaker 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 before applying the sorting algorithm. For example, if every element is at a position that differs by at most k (k ≥ 1) from the position it is going to end up in, the complexity of cocktail shaker sort becomes
The cocktail shaker sort is also briefly discussed in the book The Art of Computer Programming, along with similar refinements of bubble sort. In conclusion, Knuth states about bubble sort and its improvements:
But none of these refinements leads to an algorithm better than straight insertion [that is, insertion sort]; and we already know that straight insertion isn't suitable for large N. [...] In short, the bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical problems.
— D. E. Knuth[1]
Variations
[edit]- Dual Cocktail Shaker sort is a variant of Cocktail Shaker Sort that performs a forward and backward pass per iteration simultaneously, improving performance compared to the original.
References
[edit]- ^ a b c Knuth, Donald E. (1973). "Sorting by Exchanging". Art of Computer Programming. Vol. 3. Sorting and Searching (1st ed.). Addison-Wesley. pp. 110–111. ISBN 0-201-03803-X.
- ^ Black, Paul E.; Bockholt, Bob (24 August 2009). "bidirectional bubble sort". In Black, Paul E. (ed.). Dictionary of Algorithms and Data Structures. National Institute of Standards and Technology. Archived from the original on 16 March 2013. Retrieved 5 February 2010.
- ^ Duhl, Martin (1986). "Die schrittweise Entwicklung und Beschreibung einer Shuffle-Sort-Array Schaltung". HYPERKARL aus der Algorithmischen Darstellung des BUBBLE-SORT-ALGORITHMUS (in German). Technical University of Kaiserslautern.
{{cite book}}:|journal=ignored (help) - ^ "[JDK-6804124] (coll) Replace "modified mergesort" in java.util.Arrays.sort with timsort - Java Bug System". bugs.openjdk.java.net. Retrieved 2020-01-11.
- ^ Peters, Tim (2002-07-20). "[Python-Dev] Sorting". Retrieved 2020-01-11.
Sources
[edit]- Hartenstein, R. (July 2010). "A new World Model of Computing" (PDF). The Grand Challenge to Reinvent Computing. Belo Horizonte, Brazil: CSBC. Archived from the original (PDF) on 2013-08-07. Retrieved 2011-01-14.
External links
[edit]Cocktail shaker sort
View on GrokipediaIntroduction
Description
Cocktail shaker sort, also known as bidirectional bubble sort or shaker sort, is a stable comparison-based sorting algorithm that enhances the efficiency of bubble sort by traversing the array in both forward and backward directions.[4][5] The core mechanism involves alternating passes: a forward pass from left to right compares adjacent elements and swaps them if they are in the wrong order, effectively bubbling the largest unsorted element to the end of the array; this is followed by a backward pass from right to left, which bubbles the smallest unsorted element to the beginning.[1][4] These bidirectional traversals continue, progressively shrinking the unsorted portion of the array from both ends until no further swaps are needed.[5] The primary purpose of cocktail shaker sort is to accelerate the sorting process relative to standard bubble sort by allowing elements to move toward their final positions more quickly through dual-directional bubbling, thereby reducing the total number of passes required in many cases.[4] As a stable algorithm, it preserves the relative order of equal elements in the input, ensuring that ties are not disrupted during sorting.[5] For illustration, consider an unsorted list such as [3, 1, 4, 1, 5]: in the initial forward pass, larger elements like 5 and 4 bubble rightward, while the subsequent backward pass shifts smaller elements like the first 1 leftward, demonstrating the bidirectional movement that efficiently repositions items from both ends without fully resolving the sort in a single cycle.[1][4]History and Motivation
Cocktail shaker sort emerged in the mid-20th century as a refinement of bubble sort, amid the development of simple sorting algorithms for early computers in the 1950s and 1960s. Bubble sort itself was first described by Edward H. Friend in 1956, highlighting the need for straightforward methods in resource-limited environments.[6] The bidirectional variant, alternating passes from left to right and right to left, addressed limitations in unidirectional bubbling, with early conceptual roots in optimizing element movement during this era of computing literature.[6] No specific inventor is identified for cocktail shaker sort, as it arose from general algorithmic improvements in sorting techniques documented in programming texts. The first formal description and naming of the algorithm as "cocktail shaker sort" appeared in Donald E. Knuth's seminal work, The Art of Computer Programming, Volume 3: Sorting and Searching, published in 1973.[7] Knuth presented it as an extension of bubble sort, noting its repeated forward and backward passes to enhance efficiency. The primary motivation for developing cocktail shaker sort was to mitigate the inefficiency of bubble sort, particularly its slow migration of small elements toward the beginning of the list, which often required numerous additional passes. By incorporating reverse-direction passes, the algorithm allows smaller elements to "sink" leftward more quickly, reducing the overall number of iterations needed in certain cases.[7] This bidirectional approach draws an analogy to shaking a cocktail mixer back and forth to evenly distribute ingredients, hence the evocative name coined by Knuth.[6] In its early applications, cocktail shaker sort was primarily employed in educational contexts and for sorting small datasets within constrained systems, such as punch-card-based computers, where algorithmic simplicity outweighed computational overhead.[6] Over time, it gained prominence in teaching materials for its intuitive visualization of element swaps and movements, making it a valuable tool for illustrating sorting principles without the complexity of more advanced algorithms.[6]Algorithm
Pseudocode
Cocktail shaker sort operates on an input array of comparable elements, sorting it in place in non-decreasing (ascending) order. The algorithm assumes the array elements can be compared using a greater-than operator for pairwise swaps.[8][9] The following pseudocode illustrates the structure, using a pass counter to progressively reduce the active range of the array:procedure cocktailShakerSort(A: array of comparable elements, n: integer)
swapped ← true
pass ← 0
while swapped and pass < n do
swapped ← false
// Forward pass: bubble largest element to the right
for i ← 0 to n - pass - 2 do
if A[i] > A[i + 1] then
swap A[i] and A[i + 1]
swapped ← true
// Backward pass: bubble smallest element to the left
for i ← n - pass - 2 downto 1 do
if A[i] > A[i + 1] then
swap A[i] and A[i + 1]
swapped ← true
pass ← pass + 1
end while
end procedure
procedure cocktailShakerSort(A: array of comparable elements, n: integer)
swapped ← true
pass ← 0
while swapped and pass < n do
swapped ← false
// Forward pass: bubble largest element to the right
for i ← 0 to n - pass - 2 do
if A[i] > A[i + 1] then
swap A[i] and A[i + 1]
swapped ← true
// Backward pass: bubble smallest element to the left
for i ← n - pass - 2 downto 1 do
if A[i] > A[i + 1] then
swap A[i] and A[i + 1]
swapped ← true
pass ← pass + 1
end while
end procedure
n - pass - 2 (inclusive), ensuring the already-sorted suffix is excluded as each pass fixes the largest remaining element at the end. The backward pass then iterates from index n - pass - 2 down to 1 (inclusive), applying the same comparison to allow smaller elements to move leftward. This bidirectional traversal refines the bubble sort approach by alternating directions within each full pass. Note that this variant progressively fixes only the suffix, with the forward pass always starting from the beginning, though no swaps occur in the ordered prefix.[8][9]
The swapped flag is reset to false at the start of each full pass (forward and backward combined) and set to true upon any swap. If no swaps occur during a full forward-backward cycle, the flag remains false, and the outer loop terminates early, as the array is fully sorted. This optimization avoids unnecessary iterations when the input is nearly sorted or already ordered.[8]
Step-by-Step Execution
To illustrate the step-by-step execution of the cocktail shaker sort, consider the initial unsorted array of eight elements: [3, 1, 4, 1, 5, 9, 2, 6]. The algorithm begins with a forward pass from left to right, comparing adjacent elements and swapping them if they are in the wrong order to bubble the largest element to the end. In the first forward pass, starting at index 0 (i from 0 to 6):- Compare 3 and 1: swap to get [1, 3, 4, 1, 5, 9, 2, 6].
- Compare 3 and 4: no swap.
- Compare 4 and 1: swap to get [1, 3, 1, 4, 5, 9, 2, 6].
- Compare 4 and 5: no swap.
- Compare 5 and 9: no swap.
- Compare 9 and 2: swap to get [1, 3, 1, 4, 5, 2, 9, 6].
- Compare 9 and 6: swap to get [1, 3, 1, 4, 5, 2, 6, 9].
- Compare 6 and 9: no swap.
- Compare 2 and 6: no swap.
- Compare 5 and 2: swap to get [1, 3, 1, 4, 2, 5, 6, 9].
- Compare 4 and 2: swap to get [1, 3, 1, 2, 4, 5, 6, 9].
- Compare 1 and 2: no swap.
- Compare 3 and 1: swap to get [1, 1, 3, 2, 4, 5, 6, 9].
- Compare 1 and 1: no swap.
- Compare 1 and 3: no swap.
- Compare 3 and 2: swap to get [1, 1, 2, 3, 4, 5, 6, 9].
- Compare 3 and 4: no swap.
- Compare 4 and 5: no swap.
- Compare 5 and 6: no swap.
Comparison to Bubble Sort
Key Differences
Cocktail shaker sort, also known as bidirectional bubble sort or shaker sort, fundamentally differs from standard bubble sort in its traversal mechanism. While bubble sort performs only forward passes from the beginning to the end of the array, repeatedly bubbling the largest elements to the right until sorted, cocktail shaker sort alternates between forward passes (which move the largest unsorted element to the end) and backward passes (which move the smallest unsorted element to the beginning). This bidirectional approach allows elements to "shake" through the array in both directions, addressing misplaced small elements more efficiently than bubble sort's unidirectional method.[6][10] In terms of pass efficiency, cocktail shaker sort handles both extremities of the array simultaneously within paired passes, potentially requiring roughly half the number of iterations compared to bubble sort for certain input distributions, such as nearly sorted or reverse-ordered lists, by progressively shrinking the unsorted region from both ends. Bubble sort, by contrast, fixes only the right end per pass, leaving small elements to percolate slowly leftward over multiple forward iterations. The swap conditions also vary directionally: during forward passes, cocktail shaker sort swaps adjacent elements if the left one is greater than the right (similar to bubble sort), but in backward passes, it swaps if the right one is smaller than the left, effectively bubbling minima leftward. This contrasts with bubble sort's uniform forward-only greater-than comparison.[3][6] Both algorithms employ a swapped flag for early termination when no exchanges occur in a pass, indicating a sorted array, but cocktail shaker sort's bidirectional nature enables quicker detection of the sorted state, particularly in reverse-ordered inputs where bubble sort would require full passes to move elements left. Regarding stability, both preserve the relative order of equal elements, as swaps occur only between strictly unequal adjacent pairs; however, cocktail shaker sort maintains this property without incurring extra computational overhead from its additional backward passes, as the operations remain comparison-based and adjacent.[10][3]Performance Implications
In the best-case scenario, where the input list is already sorted, cocktail shaker sort completes after a single forward-backward pass, as no swaps occur and the sorted flag prevents further iterations; this mirrors bubble sort's early termination but benefits from confirming order from both ends simultaneously, potentially allowing quicker detection of sortedness in practice.[11] For the worst-case scenario of a reverse-sorted list, the algorithm remains quadratic in time complexity, requiring roughly n(n-1)/2 comparisons like bubble sort, but the backward pass accelerates the movement of small elements toward the front, resulting in fewer overall swaps compared to unidirectional bubble sort.[11] In the average case with random data, empirical evaluations demonstrate that cocktail shaker sort outperforms bubble sort by reducing the number of passes needed, as elements are progressively fixed at both ends of the array more efficiently; studies report that it is typically less than twice as fast as bubble sort, with notable reductions in comparisons and swaps due to the bidirectional approach.[11][12] Practically, cocktail shaker sort excels with nearly sorted data, where its dual-direction passes minimize unnecessary traversals and provide clearer visualization of progress from both array ends, which aids in debugging and educational contexts; however, it remains fundamentally quadratic and unsuitable for large datasets (n > 1000), lacking advanced adaptive features beyond the no-swap flag.[11]Analysis
Time Complexity
The time complexity of cocktail shaker sort is analyzed by considering the number of comparisons and swaps performed across its bidirectional passes, which determine the overall runtime since each operation takes constant time. In the worst case, typically occurring with a reverse-sorted input, the algorithm requires the maximum number of passes to propagate elements to their correct positions. It performs up to full forward-backward cycles, where each cycle shrinks the unsorted range by one element from each end. The total number of comparisons is exactly , matching that of bubble sort. To derive this, note that in the -th cycle (starting from ), the forward pass performs comparisons, and the backward pass performs comparisons, for to where . Summing these yields: Substituting simplifies to . Thus, the worst-case time complexity is .[3][2] In the best case, when the input is already sorted, the algorithm detects no swaps after the first forward-backward passes (using a swapped flag for early termination) and halts. This involves approximately comparisons, yielding a linear time complexity of .[3][2] For the average case over random permutations, the expected number of passes is still due to the quadratic nature of the nested loops, resulting in time complexity. However, the bidirectional passes reduce the constant factor compared to bubble sort by fixing elements at both ends more efficiently, leading to approximately comparisons on average, though with fewer actual passes for typical inputs. The exact count depends on the input distribution; for instance, nearly sorted or random data requires fewer iterations than reverse-ordered sequences, while adversarial distributions maximize the pass count.[3]Space Complexity
Cocktail shaker sort is an in-place sorting algorithm, requiring only O(1) auxiliary space regardless of the input size. This means it uses a constant amount of extra memory beyond the original array, making it highly efficient in terms of space usage. The algorithm relies on a few simple variables, such as a boolean flag to track whether any swaps occurred in a pass, integer indices for the forward and backward traversals, and a temporary variable for swapping elements pairwise.[1][11] Unlike algorithms that require additional data structures, cocktail shaker sort operates directly on the input array without allocating new arrays or lists. All operations involve comparing and swapping adjacent elements in place during the bidirectional passes, ensuring no extra space proportional to the input size is needed. The temporary swap variable introduces only a negligible constant overhead, as it holds at most one element at a time.[1][11] In comparison to divide-and-conquer sorts like merge sort, which require O(n space for auxiliary arrays during the merging process, cocktail shaker sort's O(1) space complexity makes it particularly suitable for memory-constrained environments, such as embedded systems or when sorting large datasets in limited RAM.[13] This constant space footprint scales independently of the input size n, providing predictable memory behavior even for very large arrays.[11]Variations
Bidirectional Variants
One prominent bidirectional variant of cocktail shaker sort is the odd-even sort, also known as brick sort, which maintains the core bidirectional nature but alternates between passes over odd-indexed pairs and even-indexed pairs of elements. This approach mimics a parallel bubble sort by decoupling comparisons, reducing data dependencies and enabling potential hardware optimizations such as simultaneous execution on multi-core systems. In each phase, odd-even sort performs a forward pass on odd-even adjacent pairs (swapping if out of order), followed by a forward pass on even-odd pairs, repeating until no swaps occur. Another key variant is the flag-optimized bidirectional sort, which incorporates an early termination mechanism into the standard cocktail shaker passes by tracking swaps with a boolean flag. After each forward or backward pass, if the flag indicates no swaps were made, the algorithm concludes the array is sorted and halts, avoiding unnecessary iterations. This optimization is particularly effective for nearly sorted data, reducing the average number of passes while preserving the bidirectional movement of elements to both ends.[5] These variants retain the O(n²) worst-case time complexity of cocktail shaker sort but improve practical performance constants, especially on partially sorted lists or datasets with clustered inversions, by minimizing redundant comparisons without altering the fundamental bidirectional pass structure.[4] For implementation, the odd-even variant adapts the pseudocode by separating the passes into distinct loops for odd and even indices, as shown below:do {
swapped = false
// Odd pass
for i from 0 to n-2 step 2 {
if array[i] > array[i+1] {
swap array[i] and array[i+1]
swapped = true
}
}
// Even pass
for i from 1 to n-2 step 2 {
if array[i] > array[i+1] {
swap array[i] and array[i+1]
swapped = true
}
}
} while swapped
do {
swapped = false
// Odd pass
for i from 0 to n-2 step 2 {
if array[i] > array[i+1] {
swap array[i] and array[i+1]
swapped = true
}
}
// Even pass
for i from 1 to n-2 step 2 {
if array[i] > array[i+1] {
swap array[i] and array[i+1]
swapped = true
}
}
} while swapped

