/// <summary> /// Uses Equality check only for removing from the queue. /// Might cost O(n) if all items are in the queue and not the heap. /// </summary> /// <param name="item"></param> /// <returns></returns> public bool Remove ( IBinaryHeapItem item ) { if (item.GetIndexInHeap() == BinaryHeap.REMOVED_FROM_HEAP) // Or from queue. { return(false); } bool removedFromQueue = false; // Remove from the queue if it's there, keeping the order in the queue. for (int i = 0; i < this.queue.Count; ++i) { IBinaryHeapItem temp = this.queue.Dequeue(); if (temp.Equals(item)) { removedFromQueue = true; temp.SetIndexInHeap(BinaryHeap.REMOVED_FROM_HEAP); } else { this.queue.Enqueue(temp); } } if (removedFromQueue == true) { return(true); } return(this.heap.Remove(item)); }
/// <summary> /// Adds a key and value to the heap. /// </summary> /// <param name="item">The item to add to the heap.</param> public void Add(IBinaryHeapItem item) { if (item == null) { return; } if (_count == _capacity) { Capacity *= 2; // Automatically grows the array! } item.SetIndexInHeap(_count); _data[_count] = item; _count++; UpHeap(); }
/// <summary> /// Removes and returns the first item in the heap. /// </summary> /// <returns>The next item in the heap.</returns> public IBinaryHeapItem Remove() { if (this._count == 0) { throw new InvalidOperationException("Cannot remove item, heap is empty."); } IBinaryHeapItem v = _data[0]; v.SetIndexInHeap(REMOVED_FROM_HEAP); _count--; if (this._count != 0) { _data[0] = _data[_count]; DownHeap(); } _data[_count] = default(IBinaryHeapItem); // Clear the last node return(v); }