/// <summary> /// Union two heaps together, returns a new min-heap of both heaps' elements, /// ... and then destroys the original ones. /// </summary> public BinaryMaxHeap <T> Union(ref BinaryMaxHeap <T> firstMaxHeap, ref BinaryMaxHeap <T> secondMaxHeap) { if (firstMaxHeap == null || secondMaxHeap == null) { throw new ArgumentNullException("Null heaps are not allowed."); } // Create a new heap with reserved size. int size = firstMaxHeap.Count + secondMaxHeap.Count; var newHeap = new BinaryMaxHeap <T>(size, Comparer <T> .Default); // Insert into the new heap. while (firstMaxHeap.IsEmpty == false) { newHeap.Add(firstMaxHeap.ExtractMax()); } while (secondMaxHeap.IsEmpty == false) { newHeap.Add(secondMaxHeap.ExtractMax()); } // Destroy the two heaps. firstMaxHeap = secondMaxHeap = null; return(newHeap); }
/// <summary> /// Returns a new max heap that contains all elements of this heap. /// </summary> public IMaxHeap <T> ToMaxHeap() { BinaryMaxHeap <T> newMaxHeap = new BinaryMaxHeap <T>(this.Count, this._heapComparer); newMaxHeap.Initialize(this._collection.ToArray()); return(newMaxHeap); }