示例#1
0
    /**
     *  Turns the tree back into a heap, provided only the root
     *  node violates the heap condition.
     */
    private void fixHeap()
    {
        NodoAE root = elements[1];

        int lastIndex = elements.Count - 1;
        // Promote children of removed root while they are larger than last

        int  index = 1;
        bool more  = true;

        while (more)
        {
            int childIndex = getLeftChildIndex(index);
            if (childIndex <= lastIndex)
            {
                // Get smaller child

                // Get left child first
                NodoAE child = getLeftChild(index);

                // Use right child instead if it is smaller
                if (getRightChildIndex(index) <= lastIndex && getRightChild(index).CompareTo(child) < 0)
                {
                    childIndex = getRightChildIndex(index);
                    child      = getRightChild(index);
                }

                // Check if larger child is smaller than root
                if (child.CompareTo(root) < 0)
                {
                    // Promote child
                    elements[index] = child;
                    index           = childIndex;
                }
                else
                {
                    // Root is smaller than both children
                    more = false;
                }
            }
            else
            {
                // No children
                more = false;
            }
        }

        // Store root element in vacant slot
        elements[index] = root;
    }