Sunday, December 5, 2010

Pigeonhole Sort

Pigeonhole sorting, also known as count sort (not to be confused with counting sort), is a sorting algorithm that is suitable for sorting lists of elements where the number of elements (n) and the number of possible key values (N) are approximately the same. It requires O(n + N) time.

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 through the range of 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 order, and put elements from non-empty pigeonholes back into the original array.

public IList PigeonHoleSort(IList list)
{
    object min = list[0], max = list[0];
    foreach (object x in list)
    {
        if (((IComparable)min).CompareTo(x) > 0)
        {
            min = x;
        }
        if (((IComparable)max).CompareTo(x) < 0)
        {
            max = x;
        }
        Thread.Sleep(speed);
    }

    int size = (int)max - (int)min + 1;

    int[] holes = new int[size];

    foreach (int x in list)
        holes[x - (int)min]++;

    int i = 0;
    for (int count = 0; count < size; count++)
        while (holes[count]-- > 0)
        {

            list[i] = count + (int)min;
            RedrawItem(i);
            i++;
            RefreshPanel(pnlSamples);
            Thread.Sleep(speed);
        }
    return list;
}

No comments:

Post a Comment