Hubbry Logo
Cocktail shaker sortCocktail shaker sortMain
Open search
Cocktail shaker sort
Community hub
Cocktail shaker sort
logo
8 pages, 0 posts
0 subscribers
Be the first to start a discussion here.
Be the first to start a discussion here.
Cocktail shaker sort
Cocktail shaker sort
from Wikipedia
Cocktail shaker sort
Visualization of shaker sort
ClassSorting algorithm
Data structureArray
Worst-case performance
Best-case performance
Average performance
Worst-case space complexity
OptimalNo

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]

Sources

[edit]
[edit]
Revisions and contributorsEdit on WikipediaRead on Wikipedia
from Grokipedia
Cocktail shaker sort, also known as shaker sort or bidirectional bubble sort, is a comparison-based that extends the bubble sort by performing multiple passes over the data in alternating directions—first from left to right to move larger elements toward the end, and then from right to left to move smaller elements toward the beginning—repeatedly swapping adjacent elements if they are in the wrong order until the array is fully sorted. This algorithm improves upon the standard bubble sort by reducing the number of passes required in certain cases, particularly when small elements are trapped at the end of the array, as the backward pass allows them to propagate leftward more efficiently. Like bubble sort, it has a of O(n²) in the worst and average cases due to the quadratic number of comparisons and swaps, but it can achieve O(n) performance on nearly sorted data by incorporating an early termination condition when no swaps occur in a full forward-backward cycle. The is O(1), making it an in-place sorting method suitable for with limited . Despite these optimizations, cocktail shaker sort remains inefficient for large datasets compared to more advanced algorithms like or mergesort, and its primary value lies in educational contexts for illustrating incremental improvements to simple sorting techniques. It was notably discussed in early computing literature, including references in Donald Knuth's , highlighting its role as a refined variant of bubble sort.

Introduction

Description

Cocktail shaker sort, also known as bidirectional bubble sort or shaker sort, is a comparison-based that enhances the efficiency of bubble sort by traversing the array in both forward and backward directions. The core mechanism involves alternating passes: a 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. These bidirectional traversals continue, progressively shrinking the unsorted portion of the array from both ends until no further swaps are needed. 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. As a , it preserves the relative order of equal elements in the input, ensuring that ties are not disrupted during sorting. For illustration, consider an unsorted list such as [3, 1, 4, 1, 5]: in the initial , 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.

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 and 1960s. Bubble sort itself was first described by H. Friend in 1956, highlighting the need for straightforward methods in resource-limited environments. 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. 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, , published in 1973. Knuth presented it as an extension of , 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, allows smaller elements to "sink" leftward more quickly, reducing the overall number of iterations needed in certain cases. 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. 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 outweighed computational overhead. 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.

Algorithm

Pseudocode

Cocktail shaker sort operates on an input of comparable elements, sorting it in place in non-decreasing (ascending) order. The algorithm assumes the elements can be compared using a greater-than operator for pairwise swaps. The following illustrates the structure, using a pass counter to progressively reduce the active range of the :

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

In the forward pass, the loop iterates from index 0 to n - pass - 2 (inclusive), ensuring the already-sorted 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 , with the forward pass always starting from the beginning, though no swaps occur in the ordered prefix. 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 is fully sorted. This optimization avoids unnecessary iterations when the input is nearly sorted or already ordered.

Step-by-Step Execution

To illustrate the step-by-step execution of the cocktail shaker sort, consider the initial unsorted 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 , 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].
The array after this pass is [1, 3, 1, 4, 5, 2, 6, 9], with the largest element (9) now fixed at the end. The bounds shrink, excluding the sorted end. The first backward pass then proceeds from right to left (i from 6 down to 1), again comparing adjacent elements and swapping if out of order to bubble the smallest element toward the beginning:
  • 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].
The array after this pass is [1, 1, 3, 2, 4, 5, 6, 9]. Swaps occurred in this full first pass (forward and backward), so it continues. For the second forward pass (pass=1, i from 0 to 5):
  • 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.
The array is now [1, 1, 2, 3, 4, 5, 6, 9]. A swap occurred in this forward pass. The second backward pass (i from 5 down to 1) yields no swaps, as all adjacent pairs are in order. However, since a swap occurred earlier in this full pass (during forward), the algorithm continues to a third pass. In the third forward pass (pass=2, i from 0 to 4), all comparisons show no swaps needed. The third backward pass (i from 4 down to 1) also yields no swaps. Since no swaps occurred in this full pass, the algorithm terminates. This bidirectional shaking process positions elements more efficiently, with larger values migrating rightward in forward passes and smaller values leftward in backward passes, often requiring fewer passes than a unidirectional approach for the same array.

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. In terms of pass efficiency, cocktail shaker sort handles both extremities of the 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. Both algorithms employ a swapped for early termination when no exchanges occur in a pass, indicating a sorted , 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.

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. 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 , but the backward pass accelerates the movement of small elements toward the front, resulting in fewer overall swaps compared to unidirectional . In the average case with random data, empirical evaluations demonstrate that outperforms 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 , with notable reductions in comparisons and swaps due to the bidirectional approach. 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 and educational contexts; however, it remains fundamentally quadratic and unsuitable for large datasets (n > 1000), lacking advanced adaptive features beyond the no-swap flag.

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 n/2\lfloor n/2 \rfloor full forward-backward cycles, where each cycle shrinks the unsorted range by one element from each end. The total number of comparisons is exactly n(n1)/2n(n-1)/2, matching that of bubble sort. To derive this, note that in the kk-th cycle (starting from k=0k=0), the forward pass performs n12kn - 1 - 2k comparisons, and the backward pass performs n22kn - 2 - 2k comparisons, for k=0k = 0 to m1m-1 where m=n/2m = \lfloor n/2 \rfloor. Summing these yields: k=0m1[(n12k)+(n22k)]=k=0m1(2n34k)=m(2n3)4m(m1)2=m(2n2m1).\sum_{k=0}^{m-1} \left[ (n-1-2k) + (n-2-2k) \right] = \sum_{k=0}^{m-1} (2n - 3 - 4k) = m(2n-3) - 4 \cdot \frac{m(m-1)}{2} = m(2n - 2m - 1). Substituting mn/2m \approx n/2 simplifies to n(n1)/2n(n-1)/2. Thus, the worst-case time complexity is O(n2)O(n^2). In the best case, when the input is already sorted, the algorithm detects no swaps after the first forward-backward passes (using a for early termination) and halts. This involves approximately 2(n1)2(n-1) comparisons, yielding a linear of O(n)O(n). For the case over random permutations, the expected number of passes is still Θ(n)\Theta(n) due to the quadratic nature of the nested loops, resulting in Θ(n2)\Theta(n^2) . However, the bidirectional passes reduce the constant factor compared to bubble sort by fixing elements at both ends more efficiently, leading to approximately n(n1)/2n(n-1)/2 comparisons on , 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.

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. 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. In comparison to divide-and-conquer sorts like , 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. This constant space footprint scales independently of the input size n, providing predictable memory behavior even for very large arrays.

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 flag. After each forward or backward pass, if the flag indicates no swaps were made, 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. These variants retain the O(n²) worst-case 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. For implementation, the odd-even variant adapts the 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

This modification skips interleaved comparisons, facilitating the bidirectional progression while enhancing adaptability to specific data patterns.

Optimized Extensions

An adaptive gap variant, known as shaker sort, draws inspiration from shell sort by applying larger initial gaps in bidirectional passes and progressively shrinking them to 1, effectively combining the gap-based comparisons of shell sort with the forward-and-backward bubbling of cocktail shaker sort. This method performs multiple up-shakes (forward passes to move large elements right) and down-shakes (backward passes to move small elements left) on subarrays separated by the gap, reducing inversions more rapidly than standard adjacent swaps. To complete sorting, it finishes with an insertion sort pass on the remaining small subarrays, leveraging insertion sort's efficiency on nearly ordered data. Empirical tests on VAX systems showed this variant achieving performance comparable to shellsort for arrays up to 5,000 elements, with about 1.5 seconds for n=1,000, though it requires twice as many comparisons per pass compared to insertion-based shellsort equivalents. For parallel processing on multi-core systems, can be adapted by dividing the into independent strips or subarrays, allowing concurrent execution of forward and backward passes across cores using frameworks like MPI for or for GPU acceleration. This division enables simultaneous bubbling in separate regions, with periodic merging or to handle boundary elements, potentially scaling performance linearly with the number of cores for large datasets. A 2022 study demonstrated this parallelization, reporting improved throughput on multi-node clusters, though overhead limits gains to moderate sizes. In real-world applications, optimized cocktail shaker sort variants appear in educational tools, such as JavaScript-based visualizations that animate bidirectional passes to teach sorting concepts interactively. These implementations, often used in online algorithm courses, highlight the algorithm's simplicity for small-scale demonstrations without requiring complex data structures. These extensions introduce trade-offs, including a slight increase in space complexity to O(log n) for storing gap sequences in adaptive variants, while potentially improving average-case time towards O(n log n) in hybrid configurations with good increment choices; however, they maintain the in-place nature of the base algorithm and may underperform on highly random large inputs compared to advanced sorts like .
Add your contribution
Related Hubs
User Avatar
No comments yet.