コード例 #1
0
        /// <summary>
        /// Gets the median based on the current elements in the stream
        /// </summary>
        /// <returns>median of the stream</returns>
        public double GetMedian()
        {
            if ((MinHeapInst.HeapSize + MaxHeapInst.HeapSize) % 2 != 0)
            {
                // odd number of elements in the stream
                return(MaxHeapInst.PeekMax());
            }
            // even number of elements in the stream
            int mid1 = MaxHeapInst.PeekMax();
            int mid2 = MinHeapInst.PeekMin();

            return(mid1 + ((mid2 - mid1) / 2.0)); // This will prevent overflow
        }
コード例 #2
0
 /// <summary>
 /// Insert a value to the stream
 /// </summary>
 /// <param name="val"></param>
 public void Insert(int val)
 {
     if (MaxHeapInst.HeapSize == 0)
     {
         MaxHeapInst.Insert(val);
         return;
     }
     if (MaxHeapInst.PeekMax() > val)                     // The val needs to go in MaxHeap
     {
         if (MaxHeapInst.HeapSize > MinHeapInst.HeapSize) // Make sure MaxHeap.Count does not go beyond MinHeap.Count + 1
         {
             MinHeapInst.Insert(MaxHeapInst.ExtractMax());
         }
         MaxHeapInst.Insert(val);
     }
     else // The val needs to go in MinHeap
     {
         if (MinHeapInst.HeapSize == MaxHeapInst.HeapSize) // Make sure that the MinHeap.Count does not go beyond MaxHeap.Count
         {
             MaxHeapInst.Insert(MinHeapInst.ExtractMin());
         }
         MinHeapInst.Insert(val);
     }
 }