| |||||||||
Pigeonhole sorting takes linear time (O(n)), which is the best possible performance for a sort algorithm since one must inevitably look at each of the elements being sorted at least once, regardless of the sorting algorithm. However, it requires
The range must be limited to some constant times the number of elements that is being sorted to achieve the linear running time. Pigeonhole sort orders the elements by the result of this mapping.
The algorithm works as follows.
The hidden constant for this algorithm depends critically on the density of the elements in the pigeonhole array. If there are many more array elements than items to be sorted, steps 1 and 3 will be relatively slow.
Pigeonhole sort is rarely used as the requirements are rarely met and other, more flexible, and almost as fast, sorting algorithms are easier to use. In particular, the bucket sort is a more practical variation on the pigeonhole sort.
Sample C99 code for this algorithm:
Note that min and max could also easily be determined within the function.