コード例 #1
0
        /// <summary>
        /// Adds a new item to the queue
        /// </summary>
        /// <param name="node">The node to add</param>
        /// <param name="priority">The priority of the node</param>
        public void Insert(T node, int priority)
        {
            if (node == null)
            {
                return;
            }

            if (HeapContainsNode(node)) // We return if the node is either null or already in the heap
            {
                return;
            }

            if (size + 1 == heap.Length)
            {
                DoubleArray(); // If the array would get full, double it first
            }
            PriorityNode <T> n = new PriorityNode <T>(node, priority);

            int hole = ++size;                                                   // We have a hole at the end check from

            heap[0] = n;                                                         // Store the node in the 0th index so we can percolate it down

            for (; n.priority <= heap[hole / 2].priority && hole > 1; hole /= 2) // We start at the end of our tree, while our new node's priority if higher, we go up and move all the nodes down
            {
                heap[hole] = heap[hole / 2];
            }

            heap[hole] = n;
        }
コード例 #2
0
        /// <summary>
        /// Doubles the array
        /// </summary>
        private void DoubleArray()
        {
            PriorityNode <T>[] temp = new PriorityNode <T> [heap.Length * 2];
            for (int i = 1; i < heap.Length; i++)
            {
                temp[i] = heap[i];
            }

            heap = temp;
        }