Beispiel #1
0
        /// <summary>
        /// Enqueue <paramref name="newItem"/>
        /// </summary>
        public void Enqueue(PriorityQueueItem <TValue, TPriority> newItem)
        {
            if (_numItems == _capacity)
            {
                // need to increase capacity
                // grow by 50 percent
                SetCapacity((3 * Capacity) / 2);
            }

            int i = _numItems;

            ++_numItems;
            while ((i > 0) && (_prioritySign * _compareFunc(_items[(i - 1) / 2].Priority, newItem.Priority) < 0))
            {
                _items[i] = _items[(i - 1) / 2];
                i         = (i - 1) / 2;
            }

            _items[i] = newItem;

            // if (!VerifyQueue())
            // {
            //      Debug.Log("ERROR: Queue out of order!");
            // }
        }
Beispiel #2
0
        private PriorityQueueItem <TValue, TPriority> RemoveAt(int index)
        {
            PriorityQueueItem <TValue, TPriority> o = _items[index];

            --_numItems;

            // move the last item to fill the hole
            PriorityQueueItem <TValue, TPriority> tmp = _items[_numItems];

            // If you forget to clear this, you have a potential memory leak.
            _items[_numItems] = default(PriorityQueueItem <TValue, TPriority>);
            if (_numItems > 0 && index != _numItems)
            {
                // If the new item is greater than its parent, bubble up.
                int i      = index;
                int parent = (i - 1) / 2;
                while (_prioritySign * _compareFunc(tmp.Priority, _items[parent].Priority) > 0)
                {
                    _items[i] = _items[parent];
                    i         = parent;
                    parent    = (i - 1) / 2;
                }

                // if i == index, then we didn't move the item up
                if (i == index)
                {
                    // bubble down ...
                    while (i < _numItems / 2)
                    {
                        int j = (2 * i) + 1;
                        if ((j < _numItems - 1) &&
                            (_prioritySign * _compareFunc(_items[j].Priority, _items[j + 1].Priority) < 0))
                        {
                            ++j;
                        }

                        if (_prioritySign * _compareFunc(_items[j].Priority, tmp.Priority) <= 0)
                        {
                            break;
                        }

                        _items[i] = _items[j];
                        i         = j;
                    }
                }

                // Be sure to store the item in its place.
                _items[i] = tmp;
            }

            // if (!VerifyQueue())
            // {
            //     Debug.Log("ERROR: Queue out of order!");
            // }
            return(o);
        }