Pigeonhole sort
Pigeonhole sorting is a sorting algorithm that is suitable for sorting lists of elements where the number n of elements and the length N of the range of possible key values are approximately the same. It requires O time. It is similar to counting sort, but differs in that it "moves items twice: once to the bucket array and again to the final destination counting sort builds an auxiliary array then uses the array to compute each item's final destination and move the item there."
The pigeonhole algorithm works as follows:
- Given an array of values to be sorted, set up an auxiliary array of initially empty "pigeonholes", one pigeonhole for each key in the range of the keys in the original array.
- Going over the original array, put each value into the pigeonhole corresponding to its key, such that each pigeonhole eventually contains a list of all values with that key.
- Iterate over the pigeonhole array in increasing order of keys, and for each pigeonhole, put its elements into the original array in increasing order.
Implementation
Below is an implementation of Pigeonhole sort in pseudocode. This function sorts the array in-place and modifies the supplied array.function pigeonhole is
min ← min
max ← max
index ← 0
range ← max - min + 1
array tmp ← new array of length range
for i = 0 to range STEP 1
tmp = 0
for i = 0 to 'length STEP 1
tmp - min] = tmp - min] + 1
for i = 0 to range STEP 1
while tmp > 0 do'
tmp = tmp - 1
arr = i + min
index = index + 1
Example
Suppose one were sorting these value pairs by their first element:For each value between 3 and 8 we set up a pigeonhole, then move each element to its pigeonhole:
- 3:
- 4:
- 5:,
- 6:
- 7:
- 8:
The difference between pigeonhole sort and counting sort is that in counting sort, the auxiliary array does not contain lists of input elements, only counts:
- 3: 1
- 4: 0
- 5: 2
- 6: 0
- 7: 0
- 8: 1