Пример #1
0
        public static List <int> SortedMerge(int[][] files)
        {
            BinaryMaxHeap <LineItem> heap = new BinaryMaxHeap <LineItem>();
            List <int> result             = new List <int>();

            for (int i = 0; i < files.Length; i++)
            {
                if (files[i].Length > 0)
                {
                    int value = files[i][0];
                    heap.Push(value, new LineItem(value: value, fileNum: i, nextIndex: 1));
                }
            }

            while (heap.Count > 0)
            {
                LineItem item = heap.Pop();
                result.Add(item.Value);

                int fileNum   = item.FileNum;
                int fileIndex = item.NextIndex;
                if (fileIndex < files[fileNum].Length)
                {
                    int value = files[fileNum][fileIndex];
                    heap.Push(value, new LineItem(value, fileNum, fileIndex + 1));
                }
            }

            return(result);
        }
Пример #2
0
        public void OrderTest()
        {
            var array = new[] { 1, 8, 22, 7, 6, 2, 0, 5, 3, 4 };
            var heap  = new BinaryMaxHeap(array);

            Assert.IsTrue(heap.ToArray().IsSortedByDesc(), "The array is not sorted descending");
        }
Пример #3
0
        /// <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);
        }
Пример #4
0
        public void Merge_Null()
        {
            BinaryMaxHeap <int> otherBinaryMaxHeap = null;

            Assert.Throws <ArgumentNullException>(delegate
            {
                _binaryMaxHeap.Merge(otherBinaryMaxHeap);
            });
        }
Пример #5
0
        public void GetMaxTest()
        {
            var array = new[] { 1, 8, 7 };
            var heap  = new BinaryMaxHeap(array);

            var       max         = heap.GetMax();
            const int expectedMax = 8;

            Assert.IsTrue(max == expectedMax, "Invalid maximum element retrieved");
        }
Пример #6
0
        public void HeapPushTest()
        {
            var heap = new BinaryMaxHeap(new int[] { 10 });

            heap.Insert(6);
            heap.Insert(7);
            heap.Insert(8);
            heap.Insert(9);
            heap.Items.ToArray().Should().BeEquivalentTo(new int[] { 10, 9, 8, 6, 7 });
        }
Пример #7
0
        public void HeapifyUnsortedCollectionAndCheckIfExtractedInSortedOrder()
        {
            var heap = new BinaryMaxHeap <int>();

            var unsortedList = new List <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)
                {
                    unsortedList.Add(el);
                    addedElements++;
                    el += i;
                }
            }

            heap.Heapify(unsortedList);

            if (heap.Count != addedElements)
            {
                Assert.Fail("1");
            }

            int removedElements = 0;
            var max             = heap.PeekMax();

            while (!heap.IsEmpty)
            {
                if (max < heap.PeekMax())
                {
                    Assert.Fail("2");
                }

                max = heap.PopMax();
                removedElements++;
            }

            Assert.IsTrue(heap.IsEmpty &&
                          heap.Count == 0 &&
                          addedElements == removedElements);
        }
Пример #8
0
        public void ReplacingMinElementAndCheckingIfExtractedInSortedOrder()
        {
            var heap = 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)
                {
                    heap.Add(el);
                    addedElements++;
                    el += i;
                }
            }

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

            heap.ReplaceMax(int.MinValue);
            heap.ReplaceMax(int.MinValue);
            heap.ReplaceMax(int.MinValue);

            int removedElements = 0;
            var max             = heap.PeekMax();

            while (!heap.IsEmpty)
            {
                if (max < heap.PeekMax())
                {
                    Assert.Fail();
                }

                max = heap.PopMax();
                removedElements++;
            }

            Assert.IsTrue(heap.IsEmpty &&
                          heap.Count == 0 &&
                          addedElements == removedElements);
        }
Пример #9
0
        public void AddingElementsWithCustomComparerAndCheckingIfExtractedInSortedOrder()
        {
            //Creating heap with reversed comparer
            var heap = new BinaryMaxHeap <int>(Comparer <int> .Create(
                                                   (x, y) => y.CompareTo(x)));

            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)
                {
                    heap.Add(el);
                    addedElements++;
                    el += i;
                }
            }

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

            int removedElements = 0;
            // because of the reversed comparer
            var min = heap.PeekMax();

            while (!heap.IsEmpty)
            {
                if (min > heap.PeekMax())
                {
                    Assert.Fail();
                }

                min = heap.PopMax();
                removedElements++;
            }

            Assert.IsTrue(heap.IsEmpty &&
                          heap.Count == 0 &&
                          addedElements == removedElements);
        }
Пример #10
0
        public void Merge_Empty()
        {
            var list = new List <int>()
            {
                1, 5, 0, -2, 4
            };

            _binaryMaxHeap.Heapify(list);
            BinaryMaxHeap <int> otherBinaryMaxHeap = new BinaryMaxHeap <int>();

            int countBefore = _binaryMaxHeap.Count;

            _binaryMaxHeap.Merge(otherBinaryMaxHeap);

            Assert.AreEqual(countBefore, _binaryMaxHeap.Count, "Count didn't change");
        }
Пример #11
0
        public static void CheckOrderInHeap_RandomOrder_ReturnsTrue()
        {
            BinaryMaxHeap <long> maxHeap = new BinaryMaxHeap <long>(Comparer <long> .Default);

            maxHeap.Add(23);
            maxHeap.Add(42);
            maxHeap.Add(4);
            maxHeap.Add(16);
            maxHeap.Add(8);
            maxHeap.Add(1);
            maxHeap.Add(3);
            maxHeap.Add(100);
            maxHeap.Add(5);
            maxHeap.Add(7);

            var isRightOrder = IsRightOrderInHeap <long>(maxHeap);

            Assert.True(isRightOrder);
        }
Пример #12
0
        public void ExtractMaxTest()
        {
            var heap = new BinaryMaxHeap(new int[] { 4, 1, 3, 2, 16, 9, 10, 14, 8, 7 });

            heap.ExtractMax().Should().Be(16);
            heap.ExtractMax().Should().Be(14);
            heap.ExtractMax().Should().Be(10);
            heap.ExtractMax().Should().Be(9);
            heap.ExtractMax().Should().Be(8);
            heap.ExtractMax().Should().Be(7);
            heap.ExtractMax().Should().Be(4);
            heap.ExtractMax().Should().Be(3);
            heap.ExtractMax().Should().Be(2);
            heap.ExtractMax().Should().Be(1);
            Action emptyHeapPop = () => heap.ExtractMax();

            emptyHeapPop.Should().Throw <Exception>()
            .WithMessage("Heap empty");
        }
Пример #13
0
        public static void CheckOrderInHeap_DecreasingOrder_ReturnsTrue()
        {
            BinaryMaxHeap <long> maxHeap = new BinaryMaxHeap <long>(Comparer <long> .Default);

            maxHeap.Add(10);
            maxHeap.Add(9);
            maxHeap.Add(8);
            maxHeap.Add(7);
            maxHeap.Add(6);
            maxHeap.Add(5);
            maxHeap.Add(4);
            maxHeap.Add(3);
            maxHeap.Add(2);
            maxHeap.Add(1);

            var isRightOrder = IsRightOrderInHeap <long>(maxHeap);

            Assert.IsTrue(isRightOrder);
        }
Пример #14
0
        public void Add_ZeroCapacity()
        {
            var tempBinaryMaxHeap = new BinaryMaxHeap <int>(0);

            Assert.Multiple(delegate
            {
                Assert.IsTrue(tempBinaryMaxHeap.IsEmpty);
                Assert.Zero(tempBinaryMaxHeap.Count, "Count before");
                Assert.Zero(tempBinaryMaxHeap.array.Capacity, "Capacity before");
            });

            tempBinaryMaxHeap.Add(10);

            Assert.Multiple(delegate
            {
                Assert.IsFalse(tempBinaryMaxHeap.IsEmpty);
                Assert.NotZero(tempBinaryMaxHeap.Count, "Count after");
                Assert.NotZero(tempBinaryMaxHeap.array.Capacity, "Capacity after");
            });
        }
        static void Main(string[] args)
        {
            TreeNode <int>   root       = new TreeNode <int>(5);
            BinaryTree <int> binaryTree = new BinaryTree <int>(root);

            BinaryMaxHeap <int> heap = new BinaryMaxHeap <int>();

            PriorityQueue <int> queue = new PriorityQueue <int>();

            queue.Enqueue(5);
            queue.Enqueue(6);
            queue.Enqueue(4);
            queue.Enqueue(3);
            queue.Enqueue(7);

            DFS(queue.TopNode, 0);
            //Console.WriteLine(queue.Peek());
            Console.WriteLine(new string('-', 20));
            queue.Dequeue();
            DFS(queue.TopNode, 0);
        }
        static void Main(string[] args)
        {
            TreeNode<int> root = new TreeNode<int>(5);
            BinaryTree<int> binaryTree = new BinaryTree<int>(root);

            BinaryMaxHeap<int> heap = new BinaryMaxHeap<int>();

            PriorityQueue<int> queue = new PriorityQueue<int>();

            queue.Enqueue(5);
            queue.Enqueue(6);
            queue.Enqueue(4);
            queue.Enqueue(3);
            queue.Enqueue(7);

            DFS(queue.TopNode, 0);
            //Console.WriteLine(queue.Peek());
            Console.WriteLine(new string('-', 20));
            queue.Dequeue();
            DFS(queue.TopNode, 0);
        }
Пример #17
0
        public void Merge_NotEmpty()
        {
            var list = new List <int>()
            {
                1, 5, 0, -2, 4
            };

            _binaryMaxHeap.Heapify(list);
            BinaryMaxHeap <int> otherBinaryMaxHeap = new BinaryMaxHeap <int>();

            list = new List <int>()
            {
                4, 32, -5
            };
            otherBinaryMaxHeap.Heapify(list);

            int countBefore = _binaryMaxHeap.Count;

            _binaryMaxHeap.Merge(otherBinaryMaxHeap);

            Assert.Greater(_binaryMaxHeap.Count, countBefore, "Count changed");
        }
Пример #18
0
        public static bool IsRightOrderInHeap <T>(BinaryMaxHeap <T> binaryMaxHeap) where T : IComparable <T>
        {
            var array = binaryMaxHeap.ToArray();

            for (int i = 0; i * 2 + 1 < array.Length; ++i)
            {
                int leftChildIndex  = i * 2 + 1;
                int rightChildIndex = leftChildIndex + 1;

                if (array[i].CompareTo(array[leftChildIndex]) < 0)
                {
                    return(false);
                }

                if (rightChildIndex < array.Length && array[i].CompareTo(array[rightChildIndex]) > 0)
                {
                    return(true);
                }
            }

            return(true);
        }
Пример #19
0
        public void Add_ArrayFull()
        {
            var tempBinaryMaxHeap = new BinaryMaxHeap <int>(4);
            var list = new List <int>()
            {
                1, 4, 3, 5
            };

            tempBinaryMaxHeap.Heapify(list);
            Assert.Multiple(delegate
            {
                Assert.AreEqual(4, tempBinaryMaxHeap.Count, "Count before");
                Assert.AreEqual(4, tempBinaryMaxHeap.array.Capacity, "Capacity before");
            });
            var before = tempBinaryMaxHeap.array.Capacity;

            tempBinaryMaxHeap.Add(10);

            Assert.Multiple(delegate
            {
                Assert.Greater(tempBinaryMaxHeap.Count, before, "Count after");
                Assert.Greater(tempBinaryMaxHeap.array.Capacity, before, "Capacity after");
            });
        }
Пример #20
0
        private static void TestBinaryMaxHeap()
        {
            BinaryMaxHeap <String> heap = new BinaryMaxHeap <String>();

            heap.AddNode(3, "Tushar");
            heap.AddNode(4, "Ani");
            heap.AddNode(8, "Vijay");
            heap.AddNode(10, "Pramila");
            heap.AddNode(5, "Roy");
            heap.AddNode(6, "NTF");
            heap.PrintHeap();



            var node = heap.extractMax();

            while (node != null)
            {
                Console.WriteLine("Max Node extracted is :" + node.Data + " " + node.Weight);
                heap.PrintHeap();

                node = heap.extractMax();
            }
        }
Пример #21
0
        public void HeapBuildTest()
        {
            var heap = new BinaryMaxHeap(new int[] { 4, 1, 3, 2, 16, 9, 10, 14, 8, 7 });

            heap.Items.ToArray().Should().BeEquivalentTo(new int[] { 16, 14, 10, 8, 7, 9, 3, 2, 4, 1 });
        }
Пример #22
0
        public void Constructor_Value()
        {
            var binaryMaxHeap = new BinaryMaxHeap <int>(1);

            Assert.AreEqual(1, binaryMaxHeap.array.Capacity, "Capacity");
        }
Пример #23
0
 public void SetUp()
 {
     _binaryMaxHeap = new BinaryMaxHeap <int>();
 }
Пример #24
0
 public void TearDown()
 {
     _binaryMaxHeap = null;
 }
Пример #25
0
        public void AddingAfterClearingHeap()
        {
            var heap = 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)
                {
                    heap.Add(el);
                    addedElements++;
                    el += i;
                }
            }

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

            heap.Clear();

            if (heap.Count != 0)
            {
                Assert.Fail();
            }

            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)
                {
                    heap.Add(el);
                    addedElements++;
                    el += i;
                }
            }

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

            int removedElements = 0;
            var max             = heap.PeekMax();

            while (!heap.IsEmpty)
            {
                if (max < heap.PeekMax())
                {
                    Assert.Fail();
                }

                max = heap.PopMax();
                removedElements++;
            }

            Assert.IsTrue(heap.IsEmpty &&
                          heap.Count == 0 &&
                          addedElements == removedElements);
        }
Пример #26
0
        public void MergingTwoHeapsAndCheckingIfExtractedInSortedOrder()
        {
            var heap1 = new BinaryMaxHeap <int>();
            var heap2 = new BinaryMaxHeap <int>();

            int maxElementInFirstHeap    = 100000;
            int minElementInFirstHeap    = 0;
            int addedElementsInFirstHeap = 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 = minElementInFirstHeap;
                while (el <= maxElementInFirstHeap)
                {
                    heap1.Add(el);
                    addedElementsInFirstHeap++;
                    el += i;
                }
            }

            int maxElementInSecondHeap    = 50000;
            int minElementInSecondHeap    = -50000;
            int addedElementsInSecondHeap = 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 = minElementInSecondHeap;
                while (el <= maxElementInSecondHeap)
                {
                    heap2.Add(el);
                    addedElementsInSecondHeap++;
                    el += i;
                }
            }

            if (heap1.Count != addedElementsInFirstHeap)
            {
                Assert.Fail("first heap incorrect count");
            }
            if (heap2.Count != addedElementsInSecondHeap)
            {
                Assert.Fail("second heap incorrect count");
            }

            var oldHeap = new BinaryMaxHeap <int>();

            oldHeap.Heapify(heap1.ToArray());

            heap1.Merge(heap2);
            heap2.Merge(oldHeap);

            int mergedHeapElements = addedElementsInFirstHeap + addedElementsInSecondHeap;

            if (heap1.Count != mergedHeapElements)
            {
                Assert.Fail("merged first with second incorect count");
            }
            if (heap2.Count != mergedHeapElements)
            {
                Assert.Fail("merged second with first incorrect count");
            }

            var max1 = heap1.PeekMax();
            var max2 = heap2.PeekMax();

            if (max1 != max2)
            {
                Assert.Fail("merged heaps min element is different");
            }

            int removedElements = 0;

            while (!heap1.IsEmpty && !heap2.IsEmpty)
            {
                if (max1 < heap1.PeekMax())
                {
                    Assert.Fail();
                }
                if (max2 < heap2.PeekMax())
                {
                    Assert.Fail();
                }

                max1 = heap1.PopMax();
                max2 = heap2.PopMax();
                removedElements++;

                if (max1 != max2)
                {
                    Assert.Fail("merged heaps min element is different");
                }
            }

            Assert.IsTrue(heap1.IsEmpty &&
                          heap2.IsEmpty &&
                          heap1.Count == 0 &&
                          heap2.Count == 0 &&
                          mergedHeapElements == removedElements);
        }
Пример #27
0
        public void GetMaxTest()
        {
            var heap = new BinaryMaxHeap(new int[] { 4, 1, 3, 2, 16, 9, 10, 14, 8, 7 });

            heap.GetMax().Should().Be(16);
        }
Пример #28
0
        public void Constructor_Empty()
        {
            var binaryMaxHeap = new BinaryMaxHeap <int>();

            Assert.Zero(binaryMaxHeap.array.Capacity, "Capacity");
        }
Пример #29
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);
        }