/// <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> /// Removes an item from the binary heap. /// Assumes item is or was in the heap. Doesn't use Equality checks. /// This will not remove duplicates. /// </summary> /// <param name="item">The item to be removed.</param> /// <returns>Boolean true if the item was removed.</returns> public bool Remove(IBinaryHeapItem item) { if (item == null) { return(false); } int child_index = item.GetIndexInHeap(); if (child_index == REMOVED_FROM_HEAP) { return(false); } _data[child_index].SetIndexInHeap(REMOVED_FROM_HEAP); if (child_index == 0) // This seems unnecessary { Remove(); return(true); } IBinaryHeapItem to_remove = _data[child_index]; // Bubble to_remove up the heap // If UpHeap received an index parameter instead of always starting from the last element, // we could maybe remove some code duplication. int father_index = Parent(child_index); while (child_index != 0) { _data[child_index] = _data[father_index]; // Swap parent down _data[child_index].SetIndexInHeap(child_index); child_index = father_index; father_index = Parent(child_index); } //we got to 0 _data[0] = to_remove; Remove(); // Ignoring the returned value. return(true); }
/// <summary> /// Assumes item was added to the open list in the past /// </summary> /// <param name="item"></param> /// <returns></returns> public bool Contains(IBinaryHeapItem item) { return(item.GetIndexInHeap() != BinaryHeap.REMOVED_FROM_HEAP); }