Heap Sort

private void HeapSort(long[] inputArray)
{
    for (int index = (inputArray.Length / 2) - 1; index >= 0; index--)
        Heapify(inputArray, index, inputArray.Length);
    for (int index = inputArray.Length - 1; index >= 1; index--)
    {
        SwapWithTemp(ref inputArray[0], ref inputArray[index]);
        Heapify(inputArray, 0, index - 1);
    }
}

private void Heapify(long[] inputArray, int root, int bottom)
{
    bool completed = false;
    int maxChild;

    while((root*2 <= bottom) && (!completed))
    {
        if (root * 2 == bottom)
            maxChild = root * 2;
        else if (inputArray[root * 2] > inputArray[root * 2 + 1])
            maxChild = root * 2;
        else
            maxChild = root * 2 + 1;
        if (inputArray[root] < inputArray[maxChild])
        {
            SwapWithTemp(ref inputArray[root], ref inputArray[maxChild]);
            root = maxChild;
        }
        else
        {
            completed = true;
        }
    }
}
Next PostNewer Post Previous PostOlder Post Home

0 comments:

Post a Comment