Example #1
0
        //
        // Swaps two nodes in the array
        // Necessary since we need to update the indices of the nodes in the array (for decreaseKey)
        //
        private void Swap(int index1, int index2)
        {
            // Swap the nodes
            HeapNode <int> temp = heap[index1];

            heap[index1] = heap[index2];
            heap[index2] = temp;

            // Update the array indices
            heap[index1].degree = index1;
            heap[index2].degree = index2;
        }
Example #2
0
        //
        // Makes the given node priority the newKey value and updates the heap
        // O(log n)
        //
        public void DecreaseKey(HeapNode <int> node, int newKey)
        {
            int index = node.degree;

            node.key = newKey;

            // Moves the value up the heap until a suitable point is determined
            while (index > 0 && heap[ParentIndex(index)].key <= heap[index].key)
            {
                Swap(index, ParentIndex(index));
                index = ParentIndex(index);
            }
        }
Example #3
0
        //
        // Creates the Max-heap array and places the smallest value possible in array position 0
        //
        public MaxHeap(int sz)
        {
            heap  = new HeapNode <int> [sz + 5]; // +5 for safety
            Count = 0;

            //
            // Make index 0 a sentinel value
            //
            HeapNode <int> node = new HeapNode <int>(-1);

            node.key = Double.PositiveInfinity;
            heap[0]  = node;
        }
Example #4
0
        //
        // Inserts an element (similar to Insertion; update the heap)
        // O(log n)
        //
        public void Insert(HeapNode <int> node, int key)
        {
            // Add the node to the last open position
            node.key    = key;
            node.degree = ++Count;
            heap[Count] = node;

            // Moves the value up the heap until a suitable point is determined
            int current = Count;

            while (heap[current].key >= heap[ParentIndex(current)].key)
            {
                Swap(current, ParentIndex(current));
                current = ParentIndex(current);
            }
        }
Example #5
0
        public int degree; // number of children in Fibonacci Heap; index in the min-heap

        public HeapNode(T data)
        {
            right     = this;
            left      = this;
            this.data = data;
        }