Post

Pigeonhole Sort in Java

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

Pigeonhole Sort in Java

Introduction

Pigeonhole Sort is a non-comparison sort for integers. It sets up one pigeonhole for every possible value, drops each value into the hole with its own number, and then reads the holes in order. It never compares two values with each other.

Three ideas carry the whole algorithm:

  • One hole per value: the hole for value v collects every copy of v. Holes are numbered, so their order is the sorted order.
  • Distribute: one pass over the array puts every value into its hole, in $O(1)$ per value.
  • Collect: one pass over the holes, from the lowest to the highest, copies the values back into the array.

Pigeonhole Sort is the simplest of the distribution sorts. It is closely related to Counting Sort, which keeps only a count per value instead of the values themselves, and to Bucket Sort, where each bucket covers a range of values and has to be sorted afterwards. Keeping the actual values is what makes Pigeonhole Sort useful for records sorted by a small integer key, such as students by grade or orders by priority.

This article uses Pigeonhole Sort with one ArrayList per value from 0 to the maximum, for arrays of non-negative int values.

Performance Characteristics

Pigeonhole Sort never compares values, so its cost depends only on the number of values and on the number of holes, which is set by the largest value.

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 and $k$ is the number of pigeonholes, here $\max + 1$.

CaseTimeWhen it happens
Best$O(n + k)$Any input: the same three passes run every time
Average$O(n + k)$Any input
Worst$O(n + k)$Any input, but slow when the largest value is much larger than $n$

Why $n + k$? Finding the maximum and distributing the values each walk the array once ($n$ work). Creating the holes and reading them back each walk all $k$ holes, even the empty ones. When $k$ is close to $n$, the sort is linear; when the largest value is huge, the holes dominate.

Pigeonhole Sort is only a good fit when the range of values is about as small as the number of values. Ten values up to 10,000,000 need ten million holes. For a wide range, use Radix Sort or a comparison sort.

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 + k)$: $k$ lists, which together hold all $n$ values
In placeNo (the values are copied into the holes and back)
StableYes (values join their hole in array order and leave it in the same order)

Algorithm (Pseudo Code)

Pigeonhole Sort starts by finding the largest value and creating one empty hole for every value from 0 up to it. It then walks through the array and drops each value into the hole with its own number; several copies of the same value simply share a hole, in the order they were found.

Then the holes are read from hole 0 upwards. Every value in a hole is copied back into the array at the next free position, and empty holes are skipped. Because hole v holds only the value v, and the holes are read in increasing order, the values come back in sorted order.

1
2
3
4
5
6
7
8
9
10
11
sort(array):
    checkForNegativeInput(array)
    max = largest value
    pigeonHoles = max + 1 empty lists
    for each element in array:
        pigeonHoles[element].add(element)
    index = 0
    for each hole in pigeonHoles, from 0 to max:
        for each element in hole:
            array[index++] = element
    return array

After the distribution, hole v holds every copy of the value v and nothing else, so reading the holes in order gives the sorted array.

The holes start at 0, not at the smallest value. For values between 1 and 5 that wastes one hole; for values between 1,000,000 and 1,000,010 it wastes a million. The textbook version subtracts the minimum, as the Counting Sort guide’s code does, and needs only $\max - \min + 1$ holes.

Visualization

The visualization below follows the Java code line by line, starting with ten values between 1 and 5.

Pigeonhole Sort is about values sharing holes, so instead of the values 0 to 9, the visualization starts with [4, 2, 5, 4, 1, 3, 2, 4, 5, 2]. Tick Add 5 to every value to see how many empty holes the code creates when the values don’t start near 0.

Each step shows the array, the pigeonholes 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 new random values between 0 and 6.
  • Pigeonholes: each column is one hole, numbered below; a dashed column is empty. The highlighted hole is the one being filled or read.
  • Pointer: I is index, the next position in the array to be written.
  • Colours: the value being read is amber, a value being dropped into a hole or copied back is salmon, and values back in the array are green.
  • Holes: the footer shows how many pigeonholes the code created.
read dropped / copied back in the array I = index

Java Code

The implementation is a PigeonholeSort utility class: it is final, has a private constructor, and offers one public static method, sort, for int arrays. Four private methods split up the work: checkForNegativeInput rejects negative values, createPigeonHoles creates the empty holes, populatePigeonHoles distributes the values, and collectFromPigeonHoles copies them back. The class doesn’t use the SortUtils helpers.

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

sort

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static int[] sort(int[] array) {

    checkForNegativeInput(array);

    if (array.length == 0) {
        return array;
    }

    final int maxElement = Arrays.stream(array).max().orElseThrow();
    final List<List<Integer>> pigeonHoles = createPigeonHoles(maxElement);

    populatePigeonHoles(array, pigeonHoles);
    collectFromPigeonHoles(array, pigeonHoles);

    return array;
}

sort is the entry point. It checks for negative values first, returns an empty array straight back, and finds the largest value with a stream. It then creates the holes, fills them and empties them back into the array. The same array is returned, sorted in place.

The number of holes is maxElement + 1, whatever the smallest value is, and it is computed in int. With a 512 MB heap, sorting {10_000_000, 10_000_001} builds ten million empty lists and takes about 116 ms, values around 100_000_000 throw an OutOfMemoryError, and Integer.MAX_VALUE overflows maxElement + 1 to a negative number, so new ArrayList<>(maxElement + 1) throws an IllegalArgumentException. Creating holes only from the minimum to the maximum avoids the first two, and checking the range as a long avoids the third.

checkForNegativeInput

1
2
3
4
5
6
7
private static void checkForNegativeInput(int[] array) {
    for (final int number : array) {
        if (number < 0) {
            throw new IllegalArgumentException("Array contains negative integers.");
        }
    }
}

checkForNegativeInput throws an IllegalArgumentException as soon as it finds a negative value, because a negative value has no hole: pigeonHoles.get(-3) would throw an IndexOutOfBoundsException instead, with a less helpful message.

createPigeonHoles

1
2
3
4
5
6
7
private static List<List<Integer>> createPigeonHoles(int maxElement) {
    List<List<Integer>> pigeonHoles = new ArrayList<>(maxElement + 1);
    for (int i = 0; i <= maxElement; i++) {
        pigeonHoles.add(new ArrayList<>());
    }
    return pigeonHoles;
}

createPigeonHoles creates a list of maxElement + 1 empty lists, one for each value from 0 to maxElement, so that the hole for value v is simply pigeonHoles.get(v). The initial capacity avoids resizing the outer list while it is filled.

populatePigeonHoles

1
2
3
4
5
private static void populatePigeonHoles(int[] array, List<List<Integer>> pigeonHoles) {
    for (int element : array) {
        pigeonHoles.get(element).add(element);
    }
}

populatePigeonHoles walks the array in order and adds every value to the hole with its own number. Each int is boxed into an Integer, because Java lists can only hold objects. Values that share a hole are added in the order they appear, which is what keeps the sort stable.

collectFromPigeonHoles

1
2
3
4
5
6
7
8
private static void collectFromPigeonHoles(int[] array, Iterable<List<Integer>> pigeonHoles) {
    int index = 0;
    for (final var pigeonHole : pigeonHoles) {
        for (final int element : pigeonHole) {
            array[index++] = element;
        }
    }
}

collectFromPigeonHoles reads the holes in order, from 0 up to the maximum, and copies every value it finds back into the array at index. Empty holes cost one visit each but write nothing. When the last hole has been read, index has reached the end of the array.

Running it

1
2
3
4
int[] numbers = {4, 2, 5, 4, 1, 3, 2, 4, 5, 2};
PigeonholeSort.sort(numbers);
System.out.println(Arrays.toString(numbers));
// [1, 2, 2, 2, 3, 4, 4, 4, 5, 5]

Call the static sort method; numbers itself is sorted, and the same array is also returned. The largest value is 5, so the sort creates six holes, 0 to 5, of which hole 0 stays empty.

Summary

  • Pigeonhole Sort is a non-comparison sort for integers: it drops every value into the pigeonhole with its own number and reads the holes in order.
  • This implementation creates one ArrayList per value from 0 to the maximum, distributes the values in one pass and collects them in another.
  • After the distribution, each hole holds only copies of its own value, so reading the holes from 0 upwards gives the sorted array.
  • It runs in $O(n + k)$ time and needs $O(n + k)$ extra space, where $k$ is the largest value plus one, and it is stable but not in place.
  • Use it for small integer keys, especially when whole records must move with them. For plain integers, Counting Sort does the same with a count per value; for wide ranges, use Radix Sort or Arrays.sort().
This post is licensed under CC BY 4.0 by the author.