Post

Cocktail Shaker Sort in Java

Learn how Cocktail Shaker Sort works: its time and space complexity, the algorithm in pseudo code, and a step-by-step visualisation that follows the Java code line by line.

Cocktail Shaker Sort in Java

Introduction

Cocktail Shaker Sort is a comparison sort and a two-way variant of bubble sort. Bubble sort only walks the array from left to right. Cocktail Shaker Sort alternates: a forward pass carries the largest value to the right end, then a backward pass carries the smallest value to the left end, like a cocktail shaker going back and forth.

Three ideas carry the whole algorithm:

  • Forward and backward passes: each pass compares neighbours and swaps them when they are out of order, first from left to right, then from right to left.
  • Shrinking range: after each pass, the values beyond the last swap are in their final places, so right and left move in from both ends.
  • Last swap: remembering where the last swap happened lets a pass skip a whole sorted stretch at once, and a pass without any swap ends the sort.

The backward pass fixes bubble sort’s weak spot, turtles: small values near the end of the array. In bubble sort, a value moves only one position left per pass, so [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] needs nine passes; Cocktail Shaker Sort moves the 0 to the front in a single backward pass. It is also known as bidirectional bubble sort, shaker sort, or ripple sort, and is mainly used for teaching, or for small, nearly sorted arrays.

This article uses Cocktail Shaker Sort with last-swap boundaries: each pass returns the index of its last swap, which becomes the new right or left.

Performance Characteristics

Like bubble sort, Cocktail Shaker Sort only ever swaps neighbours, so its speed depends on how far the values are from their places, and on how many passes that takes.

Time Complexity

Time complexity describes how the number of steps an algorithm takes grows as the input gets larger.

CaseTimeWhen it happens
Best$O(n)$An already sorted array: the first forward pass makes no swaps, and the sort ends
Average$O(n^2)$Random input
Worst$O(n^2)$A reverse-sorted array: every pair is out of order

Why $n^2$? Every swap fixes exactly one pair of values that are in the wrong order, and a random array has about $n^2 / 4$ such pairs, so the number of swaps is $O(n^2)$ whatever the direction of the passes. The two directions help with the number of passes, not with the number of swaps: on average Cocktail Shaker Sort needs fewer comparisons than bubble sort, but it is still quadratic.

For small or nearly sorted arrays, Insertion Sort does the same work with fewer writes, because it shifts values instead of swapping them. Cocktail Shaker Sort is mostly worth knowing as the fix for bubble sort’s turtles.

Space Complexity

Space complexity describes how much extra memory an algorithm needs, beyond the input itself, as the input gets larger.

PropertyValue
Space$O(1)$: a few indices
In placeYes
StableYes (equal neighbours are never swapped)

Algorithm (Pseudo Code)

Cocktail Shaker Sort starts with the whole array as the unsorted range. The forward pass walks from left to right, compares each pair of neighbours, and swaps them when the right one is smaller. The largest value is carried along to the end of the range. The position of the last swap becomes the new right: everything after it was not touched, so it is already in its final place.

The backward pass then walks from right down to left and does the same in the other direction, carrying the smallest value to the front; the position of its last swap becomes the new left. The passes keep alternating, and the unsorted range shrinks from both sides. When a pass makes no swaps, right or left jumps all the way to the other boundary, the range is empty, and the array is sorted.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
sort(array):
    left = 0, right = n - 1
    while left < right:
        right = performForwardPass(array, left, right)
        left = performBackwardPass(array, left, right)

performForwardPass(array, left, right):
    last = left
    for i = left to right - 1:
        if array[i + 1] < array[i]: swap(i, i + 1), last = i
    return last

performBackwardPass(array, left, right):
    last = right
    for i = right down to left + 1:
        if array[i] < array[i - 1]: swap(i - 1, i), last = i
    return last

After each round, every value before left and after right is in its final place, and only array[left .. right] is still unsorted.

The two passes return different ends of their last swapped pair. The forward pass returns i, the left index of the pair, because the value at i + 1 is final. The backward pass returns i, the right index of the pair, because the value at i - 1 is final. Mixing them up would either skip an unsorted value or recheck a sorted one.

Visualization

The visualization below follows the Java code line by line, starting with the values 0 to 9 in shuffled order.

Each step shows the array, the boundaries, the pair being compared and the line of code that is running, with a short explanation of what just happened:

  • Step through: use the arrows to move one step forward or back, or drag the slider to jump to any step.
  • Play: press Play to run the steps automatically, and press it again to pause.
  • Shuffle: press the shuffle button to start again with a new random order.
  • Pointers: L is left and R is right, the ends of the unsorted range, and I is i, the loop index of the current pass.
  • Colours: the two neighbours being compared are amber, or salmon when they swap, and values outside [left .. right], in their final places, are green.
  • Direction: the footer shows whether the current pass goes forward (→) or backward (←), and which round it is in.
  • Turtle input: tick Turtle input to sort [1, 2, 3, 4, 5, 6, 7, 8, 9, 0], where the 0 at the end is a turtle.
compared swapped final place L = left I = i R = right

Java Code

The implementation is a CocktailShakerSort class with one public method, sort, and two private methods: performForwardPass carries large values to the right, and performBackwardPass carries small values to the left. Each returns the index of its last swap, which sort uses as the new boundary. Two small helpers, swap and less, live in a separate SortUtils class.

The complete code is in the algorithm-examples repository on GitHub: CocktailShakerSort.java, with the helpers in SortUtils.java.

sort

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Override
public <T extends Comparable<T>> T[] sort(final T[] array) {
    if (array.length == 0) {
        return array;
    }

    int left = 0;
    int right = array.length - 1;

    while (left < right) {
        right = performForwardPass(array, left, right);
        left = performBackwardPass(array, left, right);
    }

    return array;
}

sort is the entry point. It accepts an array of any Comparable type, returns an empty array straight back, and otherwise starts with the whole array as the unsorted range [left .. right]. Each round of the loop runs a forward pass and a backward pass and moves both boundaries inward. When they meet, the array is sorted in place and returned.

The backward pass runs even when the forward pass has already closed the range. In that case right is not greater than left, its loop doesn’t run, and it simply returns right, which ends the while loop.

performForwardPass

1
2
3
4
5
6
7
8
9
10
11
12
private <T extends Comparable<T>> int performForwardPass(final T[] array, final int left, final int right) {
    int lastSwappedIndex = left;

    for (int i = left; i < right; i++) {
        if (SortUtils.less(array[i + 1], array[i])) {
            SortUtils.swap(array, i, i + 1);
            lastSwappedIndex = i;
        }
    }

    return lastSwappedIndex;
}

performForwardPass walks i from left to right - 1 and swaps each pair array[i], array[i + 1] that is out of order. A large value keeps winning these comparisons, so it travels all the way to the last swap position. lastSwappedIndex remembers the left index of the last swapped pair; everything after it is in order and in its final place, so it becomes the new right. If nothing is swapped, it stays at left, which closes the range.

performBackwardPass

1
2
3
4
5
6
7
8
9
10
11
12
private <T extends Comparable<T>> int performBackwardPass(final T[] array, final int left, final int right) {
    int lastSwappedIndex = right;

    for (int i = right; i > left; i--) {
        if (SortUtils.less(array[i], array[i - 1])) {
            SortUtils.swap(array, i - 1, i);
            lastSwappedIndex = i;
        }
    }

    return lastSwappedIndex;
}

performBackwardPass is the mirror image. It walks i from right down to left + 1 and swaps each pair array[i - 1], array[i] that is out of order, so a small value travels all the way to the front. lastSwappedIndex remembers the right index of the last swapped pair; everything before it is final, so it becomes the new left. Without any swap it stays at right, which closes the range.

swap and less

1
2
3
4
5
6
7
8
9
10
11
public static <T> void swap(T[] array, int i, int j) {
    if (i != j) {
        final T temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

public static <T extends Comparable<T>> boolean less(T firstElement, T secondElement) {
    return firstElement.compareTo(secondElement) < 0;
}

These helpers from SortUtils keep the passes easy to read. swap exchanges two elements, and less returns true when the first element is smaller than the second, using compareTo. Because less is strict, equal neighbours are never swapped, which makes the sort stable.

Running it

1
2
3
4
Integer[] numbers = {7, 2, 9, 4, 0, 8, 3, 6, 1, 5};
new CocktailShakerSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Create a CocktailShakerSort, pass it an array, and the same array comes back sorted, after three rounds of passes. The class is package-private, so the code must be in the com.javanibble.sort package.

Summary

  • Cocktail Shaker Sort is a two-way bubble sort: forward passes carry the largest value right, and backward passes carry the smallest value left.
  • This implementation uses last-swap boundaries: each pass returns where it last swapped, and right and left jump there, skipping any stretch that is already in order.
  • After each round, the values outside [left .. right] are in their final places, and a pass without a swap closes the range.
  • It runs in $O(n)$ on sorted input and $O(n^2)$ otherwise, needs $O(1)$ extra space, and is stable and in place.
  • It moves turtles much faster than Bubble Sort, but for real data an $O(n \log n)$ sort, or insertion sort for tiny arrays, is the better choice.
This post is licensed under CC BY 4.0 by the author.