public void BMaxHeap_Test()
        {
            var rnd = new Random();

            var initial = new List <int>(Enumerable.Range(0, 51)
                                         .OrderBy(x => rnd.Next()));

            //insert test
            var tree = new BMaxHeap <int>(initial);

            for (int i = 51; i <= 99; i++)
            {
                tree.Insert(i);
            }

            for (int i = 0; i <= 99; i++)
            {
                var Max = tree.ExtractMax();
                Assert.AreEqual(Max, 99 - i);
            }

            //IEnumerable tests.
            Assert.AreEqual(tree.Count, tree.Count());

            var testSeries = Enumerable.Range(1, 49)
                             .OrderBy(x => rnd.Next()).ToList();

            foreach (var item in testSeries)
            {
                tree.Insert(item);
            }

            for (int i = 1; i <= 49; i++)
            {
                var max = tree.ExtractMax();
                Assert.AreEqual(max, 49 - i + 1);
            }

            //IEnumerable tests.
            Assert.AreEqual(tree.Count, tree.Count());
        }
Beispiel #2
0
        /// <summary>
        /// Add a new item to stream
        /// </summary>
        /// <param name="newValue"></param>
        public void Add(int newValue)
        {
            var median = GetMedian();

            //our goal is to keep the balance factor atmost to be <=1
            if (leftHeap.Count == rightHeap.Count)
            {
                if (newValue < median)
                {
                    leftHeap.Insert(newValue);
                }
                else
                {
                    rightHeap.Insert(newValue);
                }

                return;
            }
            //left has more elements
            else if (leftHeap.Count > rightHeap.Count)
            {
                //we can't increase left count > 1
                //So borrow top to right first
                if (newValue < median)
                {
                    rightHeap.Insert(leftHeap.ExtractMax());
                    leftHeap.Insert(newValue);
                }
                else
                {
                    rightHeap.Insert(newValue);
                }

            }
            //right has more elements
            else if(rightHeap.Count > leftHeap.Count)
            {
                //we can't increase right count > 1
                //So borrow top to left first
                if (newValue > median)
                {
                    leftHeap.Insert(rightHeap.ExtractMin());
                    rightHeap.Insert(newValue);
                }
                else
                {
                    leftHeap.Insert(newValue);
                }
            }
        }
 public T Dequeue()
 {
     return(maxHeap.ExtractMax());
 }