Пример #1
0
        public void ConvertingToBinaryMinHeap()
        {
            var maxHeap = new BinaryMaxHeap <int>();

            int maxHeapElement = 50000;
            int minHeapElement = -50000;

            int addedElements = 0;

            //Adding every seventh number, then every fifth number,
            //every third and at last all numbers
            //NOTE: some items are added more than once
            for (int i = 7; i > 0; i -= 2)
            {
                int el = minHeapElement;
                while (el <= maxHeapElement)
                {
                    maxHeap.Add(el);
                    addedElements++;
                    el += i;
                }
            }

            if (maxHeap.Count != addedElements)
            {
                Assert.Fail();
            }

            // Binary max heap with reversed comparer. Have to be the same as the min heap
            var reversedMaxHeap = new BinaryMaxHeap <int>(Comparer <int> .Create(
                                                              (x, y) => y.CompareTo(x)));

            reversedMaxHeap.Heapify(maxHeap.ToArray());

            var minHeap = maxHeap.ToMinHeap();

            if (minHeap.Count != reversedMaxHeap.Count)
            {
                Assert.Fail();
            }

            var min1 = reversedMaxHeap.PeekMax();
            var min2 = minHeap.PeekMin();

            int removedElements = 0;

            while (!reversedMaxHeap.IsEmpty && !minHeap.IsEmpty)
            {
                if (min1 > reversedMaxHeap.PeekMax())
                {
                    Assert.Fail();
                }
                if (min2 > minHeap.PeekMin())
                {
                    Assert.Fail();
                }

                min1 = reversedMaxHeap.PopMax();
                min2 = minHeap.PopMin();
                removedElements++;

                if (min1 != min2)
                {
                    Assert.Fail();
                }
            }

            Assert.IsTrue(reversedMaxHeap.IsEmpty &&
                          minHeap.IsEmpty &&
                          reversedMaxHeap.Count == 0 &&
                          minHeap.Count == 0 &&
                          addedElements == removedElements);
        }