Post

Bead Sort in Java

Learn how Bead 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.

Bead Sort in Java

Introduction

Bead Sort, also called gravity sort, is a natural sorting algorithm for positive integers, inspired by an abacus. Each value is a row of beads on vertical poles: the value 4 puts one bead on each of the first four poles. When the beads are allowed to fall, they pile up at the bottom of their poles, and the rows of beads, read from top to bottom, are the values in sorted order.

Three ideas carry the whole algorithm:

  • Beads on poles: a grid with one column, or pole, per possible bead position and one row per value. The value v contributes one bead to each of poles 0 to v - 1.
  • Gravity: every bead falls as far down its pole as it can. Pole j ends up with as many beads as there are values greater than j, stacked from the bottom.
  • Reading the rows: after the fall, each row holds a run of beads starting at pole 0, the bottom row the longest and the top row the shortest. Counting the beads in each row, from the top down, gives the sorted values.

Joshua Arulanandham, Cristian Calude and Michael Dinneen described Bead Sort in 2002. Its appeal is that, in hardware or in a physical device where all beads fall at once, the sort finishes in time proportional to the height of the abacus, without comparing values at all. In software, every bead still has to be placed one at a time, so it becomes a curiosity: a striking way to see sorting as a physical process.

This article uses Bead Sort on a grid of bead states: instead of simulating the fall, each bead is placed straight onto the top of the pile on its pole, which is where it would land.

Performance Characteristics

Bead Sort’s cost depends on the number of beads and on the size of the grid, so it is governed by the size of the values, not by their order.

Time Complexity

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

In the table, $n$ is the number of values, $m$ the largest value, and $S$ the sum of all values, which is the number of beads.

CaseTimeWhen it happens
Best$O(n \cdot m)$Any input: the grid of $n \times m$ cells is created and read
Average$O(n \cdot m)$Any input
Worst$O(n \cdot m)$Any input; large values make the grid huge

Why $n \cdot m$? Placing the beads takes one step per bead, $S$ steps, and $S$ is at most $n \cdot m$. Creating the empty grid and reading back the rows also touch up to every one of the $n \cdot m$ cells. The order of the values plays no part at all. With small values, such as the digits of the visualization, this is fast; with large values, the grid explodes.

Bead Sort is only practical when the values are small. The grid holds $n \times m$ cells: with the repository code, a single value of 100,000,000, or 2,000 values up to 100,000, already throws an OutOfMemoryError with a 512 MB heap. For small integer keys, Counting Sort does the same job with one counter per value instead of a whole grid.

Space Complexity

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

PropertyValue
Space$O(n \cdot m)$ for the grid, plus $O(m)$ counters and the new result array
In placeNo (the sorted values are written to a new array)
StableNot applicable: the values are rebuilt from bead counts, so there is nothing to keep in order

Algorithm (Pseudo Code)

Bead Sort starts with an empty grid of n rows and m poles, where m is the largest value. It goes through the values one by one; a value v drops one bead onto each of the poles 0 to v - 1. On every pole, the new bead lands on top of the beads already there, so the code keeps a counter per pole with the height of its pile and puts the bead in the row the counter points to.

When every value has dropped its beads, the piles form a staircase: the bottom row has the most beads, and each row above has the same number or fewer, always starting from pole 0. The rows are then read from the top down: the number of beads in a row is one of the values, and since the rows get longer going down, the values come out from smallest to largest.

1
2
3
4
5
6
7
8
9
10
11
sort(array):
    m = largest value
    grid = n rows × m poles, all EMPTY
    count = m counters, all 0              // pile height per pole
    for each value v in array:
        for j = 0 to v - 1:
            grid[count[j]++][j] = BEAD     // drop a bead on pole j
    for i = 0 to n - 1:
        row = n - 1 - i                    // read from the top row down
        sorted[i] = number of beads in row, counted from pole 0
    return sorted

After all beads have fallen, row r, counted from the bottom, holds as many beads as the (r + 1)-th largest value, so reading the rows from the top down gives the values in ascending order.

No bead ever actually falls in this code. Because each bead is placed directly at the top of its pole’s pile, the grid ends up exactly as if gravity had acted. The physical version gets its speed from all beads falling at the same time; the software version places them one by one.

Visualization

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

Each step shows the input, the abacus, the sorted output 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.
  • Abacus: the vertical lines are the poles, numbered at the bottom, and the rows are numbered on the left, with row 0 at the bottom. Each circle is a bead.
  • Colours: the value whose beads are being dropped is amber in the input; its beads are salmon where they land. While the rows are read, the current row is highlighted, and the values read so far are green.
  • Counters: the footer shows the number of beads and the size of the grid.
value / row being read beads just dropped sorted

Java Code

The implementation is a BeadSort class with one public method, sort, for int arrays, and four private methods: allInputsMustBeNonNegative rejects negative values, fillGrid drops the beads, getEmptyGrid creates the grid, and extractSortedFromGrid reads the rows. A private enum, BeadState, marks each cell as BEAD or EMPTY. The class doesn’t use the SortUtils helpers.

The complete code is in the algorithm-examples repository on GitHub: BeadSort.java.

sort and allInputsMustBeNonNegative

1
2
3
4
5
6
7
8
9
10
public int[] sort(int[] array) {
    allInputsMustBeNonNegative(array);
    return extractSortedFromGrid(fillGrid(array));
}

private void allInputsMustBeNonNegative(final int[] array) {
    if (Arrays.stream(array).anyMatch(s -> s < 0)) {
        throw new IllegalArgumentException("BeadSort cannot sort negative numbers.");
    }
}

sort checks that no value is negative, since a negative number of beads makes no sense, then builds the grid and reads it. It returns a new array: the array passed in is left unchanged, so the caller must use the return value. Empty arrays and arrays of zeros work without a special case: the grid simply has no poles.

fillGrid and getEmptyGrid

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
private BeadState[][] fillGrid(final int[] array) {
    final var maxValue = Arrays.stream(array).max().orElse(0);
    var grid = getEmptyGrid(array.length, maxValue);

    int[] count = new int[maxValue];
    for (int i = 0, arrayLength = array.length; i < arrayLength; i++) {
        int k = 0;
        for (int j = 0; j < array[i]; j++) {
            grid[count[maxValue - k - 1]++][k] = BeadState.BEAD;
            k++;
        }
    }
    return grid;
}

private BeadState[][] getEmptyGrid(final int arrayLength, final int maxValue) {
    BeadState[][] grid = new BeadState[arrayLength][maxValue];
    for (int i = 0; i < arrayLength; i++) {
        for (int j = 0; j < maxValue; j++) {
            grid[i][j] = BeadState.EMPTY;
        }
    }

    return grid;
}

fillGrid finds the largest value, which sets the number of poles, and creates an empty grid of array.length rows by maxValue poles. count holds the height of the pile on each pole. For each value, the inner loop drops one bead on each of the poles 0 to v - 1: the bead goes into the row the pole’s counter points to, and the counter moves up. Row 0 is the bottom of the abacus.

Two details are worth noticing:

  • The counter for pole k is stored at count[maxValue - k - 1], in reverse order. That’s unusual but harmless: every pole still has exactly one counter of its own. count[k] would be the more obvious choice, and k itself is just a second name for j.
  • getEmptyGrid fills every cell with EMPTY, because a new array of enum values starts out as null. A boolean[][] would avoid both the filling loop and the cost of storing a reference per cell.

extractSortedFromGrid

1
2
3
4
5
6
7
8
9
10
11
private int[] extractSortedFromGrid(final BeadState[][] grid) {
    int[] sorted = new int[grid.length];
    for (int i = 0; i < grid.length; i++) {
        int k = 0;
        for (int j = 0; j < grid[grid.length - 1 - i].length && grid[grid.length - 1 - i][j] == BeadState.BEAD; j++) {
            k++;
        }
        sorted[i] = k;
    }
    return sorted;
}

extractSortedFromGrid reads the rows from the top, grid.length - 1, down to the bottom, row 0. In each row it counts the beads from pole 0 until the first empty cell; after the fall, the beads in a row always form one unbroken run from pole 0. That count is the next value of the sorted array, from smallest to largest.

Running it

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

Create a BeadSort, call sort, and keep the array it returns; numbers itself is unchanged. The method takes a plain int[] of non-negative values, and the grid here has 10 rows and 9 poles.

Summary

  • Bead Sort is a natural algorithm that sorts non-negative integers like beads falling on an abacus: each value becomes a row of beads, and gravity sorts the rows.
  • This implementation places every bead directly on top of the pile on its pole, using a height counter per pole, and then reads the rows from the top down.
  • After all beads have fallen, the rows form a staircase, so counting the beads per row from the top gives the values in ascending order.
  • It runs in $O(n \cdot m)$ time and space, where $m$ is the largest value, never compares two values, and returns a new array.
  • It is a memorable picture of sorting, not a practical tool: for small integers, Counting Sort is far leaner, and Arrays.sort() handles everything else.
This post is licensed under CC BY 4.0 by the author.