Pigeonhole Sort Python (original) (raw)

Last Updated : 6 Nov, 2025

Pigeonhole Sort is a simple sorting algorithm used when the number of elements (n) and the range of possible values (k) are roughly the same. It works by placing each element into a "pigeonhole" (a slot based on its value) and then reading them back in sorted order.

Working of Pigeonhole Sort

**1. Find range:

**2. Create pigeonholes: Create an array (list) of empty pigeonholes - one for each possible value in the range.

**3. Distribute elements:

**4. Reconstruct sorted list: Traverse all pigeonholes in order, putting their elements back into the original list.

Python Implementation

Python `

def pigeonhole_sort(a): mi, mx = min(a), max(a) size = mx - mi + 1 holes = [0] * size

for x in a:
    assert isinstance(x, int), "Only integers allowed"
    holes[x - mi] += 1

i = 0
for count in range(size):
    while holes[count] > 0:
        holes[count] -= 1
        a[i] = count + mi
        i += 1

a = [8, 3, 2, 7, 4, 6, 8] pigeonhole_sort(a) print(a)

`

Output

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

**Explanation: