Saturday, December 4, 2010

Heap Sort



Heapsort begins by building a heap out of the data set, and then removing the largest item and placing it at the end of the partially sorted array. After removing the largest item, it reconstructs the heap, removes the largest remaining item, and places it in the next open position from the end of the partially sorted array. This is repeated until there are no items left in the heap and the sorted array is full. Elementary implementations require two arrays - one to hold the heap and the other to hold the sorted elements.

Heapsort inserts the input list elements into a binary heap data structure. The largest value (in a max-heap) or the smallest value (in a min-heap) are extracted until none remain, the values having been extracted in sorted order. The heap's invariant is preserved after each extraction, so the only cost is that of extraction.

During extraction, the only space required is that needed to store the heap. To achieve constant space overhead, the heap is stored in the part of the input array not yet sorted.

Heapsort uses two heap operations: insertion and root deletion. Each extraction places an element in the last empty location of the array. The remaining prefix of the array stores the unsorted elements.

public IList HeapSort(IList list)
{
    for (int i = (list.Count - 1) / 2; i >= 0; i--)
        Adjust(list, i, list.Count - 1);

    for (int i = list.Count - 1; i >= 1; i--)
    {
        object Temp = list[0];
        list[0] = list[i];
        list[i] = Temp;
        RedrawItem(0);
        RedrawItem(i);
        pnlSamples.Refresh();
        if (chkCreateAnimation.Checked)
            SavePicture();
        Adjust(list, 0, i - 1);
                
    }

    return list;
}

public void Adjust(IList list, int i, int m)
{
    object Temp = list[i];
    int j = i * 2 + 1;
    while (j <= m)
    {
        if (j < m)
            if (((IComparable)list[j]).CompareTo(list[j + 1]) < 0)
                j = j + 1;

        if (((IComparable)Temp).CompareTo(list[j]) < 0)
        {
            list[i] = list[j];
            RedrawItem(i);
            pnlSamples.Refresh();
            if (chkCreateAnimation.Checked)
                SavePicture();
            i = j;
            j = 2 * i + 1;
        }
        else
        {
            j = m + 1;
        }
    }
    list[i] = Temp;
    RedrawItem(i);
    pnlSamples.Refresh();
    if (chkCreateAnimation.Checked)
        SavePicture();
}

No comments:

Post a Comment