Skip to content

Pigeonhole Sort

Sort integer keys by placing each value into a direct address slot over a small contiguous range.

Pigeonhole sort is a direct address sorting algorithm for integers in a small contiguous range. It creates one slot, or pigeonhole, for each possible key value, places elements into their matching slot, then scans the slots in order to rebuild the sorted array.

It is close to counting sort, but the usual presentation stores the actual elements in holes rather than only their counts.

Problem

Given an array AA of nn integers where every value lies in a known range [min,max][\min, \max], sort the array.

The range size is:

r=maxmin+1 r = \max - \min + 1

Idea

Allocate rr holes. Value xx maps to hole:

xmin x - \min

Then place each value into its hole and read the holes from left to right.

Algorithm

pigeonhole_sort(A):
    lo = minimum(A)
    hi = maximum(A)
    r = hi - lo + 1

    holes = [empty list for _ in range(r)]

    for x in A:
        holes[x - lo].append(x)

    i = 0
    for h from 0 to r - 1:
        for x in holes[h]:
            A[i] = x
            i += 1

    return A

Example

Let:

A=[8,3,2,7,4,6,8] A = [8, 3, 2, 7, 4, 6, 8]

Here:

min=2,max=8,r=7 \min = 2,\quad \max = 8,\quad r = 7

The holes are:

holevaluecontents
022
133
244
35empty
466
577
688, 8

Reading the holes in order gives:

[2,3,4,6,7,8,8] [2, 3, 4, 6, 7, 8, 8]

Correctness

Each element xx is placed into the unique hole whose index is xminx - \min. Therefore each hole contains exactly the elements equal to its associated value.

The final scan visits holes in increasing key order. Since all elements in earlier holes are smaller than all elements in later holes, the rebuilt array is sorted and contains exactly the original elements.

Complexity

Let:

  • nn be the number of elements
  • r=maxmin+1r = \max - \min + 1 be the range size

Time:

O(n+r) O(n + r)

Space:

O(n+r) O(n + r)

If each hole stores only a count, the space can be reduced to:

O(r) O(r)

Properties

propertyvalue
stableyes, if holes preserve insertion order
in placeno
comparison basedno
requires integer keysyes
best forsmall contiguous ranges

When to Use

Use pigeonhole sort when the input keys are integers and the range size is close to the number of elements.

It is inefficient when the range is large compared with nn, because it allocates one hole for every possible value, including values that may not appear.

Implementation (Python)

def pigeonhole_sort(a):
    if not a:
        return a

    lo = min(a)
    hi = max(a)
    holes = [[] for _ in range(hi - lo + 1)]

    for x in a:
        holes[x - lo].append(x)

    i = 0
    for hole in holes:
        for x in hole:
            a[i] = x
            i += 1

    return a