C# Implementation
suggest changepublic static class PigeonholeSort
{
public static void Sort(int[] values)
{
if (values.Length < 2) return;
int minimum = values[0];
int maximum = values[0];
foreach (int value in values)
{
minimum = System.Math.Min(minimum, value);
maximum = System.Math.Max(maximum, value);
}
// Each hole stores a frequency, so duplicates are preserved.
var holes = new int[checked(maximum - minimum + 1)];
foreach (int value in values) holes[value - minimum]++;
int destination = 0;
for (int hole = 0; hole < holes.Length; hole++)
{
while (holes[hole]-- > 0)
values[destination++] = hole + minimum;
}
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents