Peek() 공개 메소드

public Peek ( ) : Node,
리턴 Node,
예제 #1
0
        public double Solution(int x)
        {
            if (_minHeap.Count == 0)
            {
                _minHeap.Push(x, x);
            }
            else
            {
                if (x >= _minHeap.Peek().Data)
                {
                    _minHeap.Push(x, x);
                }
                else
                {
                    _maxHeap.Push(-x, x);
                }
            }

            if (_minHeap.Count > _maxHeap.Count + 1)
            {
                var min = _minHeap.Pop().Data;
                _maxHeap.Push(-min, min);
            }
            else if (_maxHeap.Count > _minHeap.Count)
            {
                var max = _maxHeap.Pop().Data;
                _minHeap.Push(max, max);
            }

            return(_minHeap.Count == _maxHeap.Count
                ? 0.5 * (_minHeap.Peek().Data + _maxHeap.Peek().Data)
                : _minHeap.Peek().Data);
        }
예제 #2
0
        public void ShouldSort__ReserveSortedInput()
        {
            var heap = new MinHeap <int>();

            heap.Insert(5);
            heap.Insert(4);
            heap.Insert(3);
            heap.Insert(2);
            heap.Insert(1);

            Assert.That(heap.Peek(), Is.EqualTo(1));
            Assert.That(heap.Extract(), Is.EqualTo(1));

            Assert.That(heap.Peek(), Is.EqualTo(2));
            Assert.That(heap.Extract(), Is.EqualTo(2));

            Assert.That(heap.Peek(), Is.EqualTo(3));
            Assert.That(heap.Extract(), Is.EqualTo(3));

            Assert.That(heap.Peek(), Is.EqualTo(4));
            Assert.That(heap.Extract(), Is.EqualTo(4));

            Assert.That(heap.Peek(), Is.EqualTo(5));
            Assert.That(heap.Extract(), Is.EqualTo(5));
        }
        public void TestContains()
        {
            int[]         heapArr = { };
            MinHeap <int> pq      = new MinHeap <int>(heapArr);

            for (int i = 1; i <= 100; ++i)
            {
                Assert.IsFalse(pq.Contains(i));
            }

            for (int i = 1; i <= 100; ++i)
            {
                pq.Insert(i);
            }

            for (int i = 1; i <= 100; ++i)
            {
                Assert.IsTrue(pq.Contains(i));
            }

            for (int i = 101; i <= 200; ++i)
            {
                Assert.IsFalse(pq.Contains(i));
            }

            Assert.IsTrue(pq.Contains(1));
            Assert.AreEqual(1, pq.Peek());

            pq.Pop();

            Assert.IsFalse(pq.Contains(1));
            Assert.AreEqual(2, pq.Peek());
        }
예제 #4
0
        public void Peek_HeapIsEmpty()
        {
            Exception e = Assert.Throws <Exception>(delegate
            {
                testMinHeap.Peek();
            });

            Assert.That(e.Message, NUnit.Framework.Does.StartWith("The heap is empty."));
        }
예제 #5
0
        /// <summary>
        /// Find median of 2 sorted arrays balancing heaps
        /// </summary>
        /// <param name="nums"></param>
        /// <returns></returns>
        public static double FindMedianSortedArrays(int[] nums1, int[] nums2)
        {
            var minHeap = new MinHeap <int>();
            var maxHeap = new MaxHeap <int>();

            // An integer from the array is first added to the minheap.
            int i = 0, j = 0;

            for (; i < nums1.Length && j < nums2.Length;)
            {
                int nextNum;
                if (nums1[i] > nums2[j])
                {
                    nextNum = nums2[j];
                    j++;
                }
                else
                {
                    nextNum = nums1[i];
                    i++;
                }

                BalanceHeaps(minHeap, maxHeap, nextNum);
            }

            while (i < nums1.Length)
            {
                BalanceHeaps(minHeap, maxHeap, nums1[i]);
                i++;
            }

            while (j < nums2.Length)
            {
                BalanceHeaps(minHeap, maxHeap, nums2[j]);
                j++;
            }

            // In the end, the median is found by using the peek element from min-heap and peek element from the max-heap
            double median;

            if (minHeap.Count() == maxHeap.Count())
            {
                median = (minHeap.Peek() + maxHeap.Peek()) / 2.0;
            }
            else if (minHeap.Count() > maxHeap.Count())
            {
                median = minHeap.Peek();
            }
            else
            {
                median = maxHeap.Peek();
            }

            return(median);
        }
        public void TestCtor()
        {
            int[]         heapArr = { 1, 2, 3, 4, 5, 6 };
            MinHeap <int> pq1     = new MinHeap <int>(heapArr);

            Assert.AreEqual(1, pq1.Peek());
            Assert.AreEqual(6, pq1.HeapSize());

            double[]         heapArr2 = { -1.0, 2.1, -3.5, 43, -1.5, 60, 0.001 };
            MinHeap <double> pq2      = new MinHeap <double>(heapArr2);

            Assert.IsTrue(Math.Abs(pq2.Peek() - (-3.5)) < 0.0000001);
            Assert.AreEqual(7, pq2.HeapSize());

            string[]         heapArr3 = { "this", "is", "a", "heap", "of", "strings" };
            MinHeap <string> pq3      = new MinHeap <string>(heapArr3);

            Assert.AreEqual("a", pq3.Peek());
            Assert.AreEqual(6, pq3.HeapSize());

            float[] heapArr4 = null;
            try
            {
                MinHeap <float> pq4 = new MinHeap <float>(heapArr4);

                Assert.Fail(
                    "Initializing a minHeap with a null array " +
                    "should have thrown an exception.");
            }
            catch (HeapException e) { }

            MinHeap <string> pq5 = new MinHeap <string>();

            try
            {
                pq5.Peek();
                Assert.Fail("Heap underflow should have thrown exception");
            }
            catch (HeapException e) { }

            try
            {
                pq5.Pop();
                Assert.Fail("Heap underflow should have thrown exception");
            }
            catch (HeapException e) { }

            pq5.Insert("hello");

            Assert.AreEqual(1, pq5.HeapSize());
            Assert.AreEqual("hello", pq5.Peek());
            Assert.AreEqual("hello", pq5.Pop());
            Assert.AreEqual(0, pq5.HeapSize());
        }
예제 #7
0
        static void GetMedian(Stream ip)
        {
            int val;

            MinHeap <int> rHeap = new MinHeap <int>();
            MaxHeap <int> lHeap = new MaxHeap <int>();

            double runningMedian = 0.0;

            while ((val = ip.Next()) != -1)
            {
                if (rHeap.Count == lHeap.Count)
                {
                    if (val < runningMedian)
                    {
                        lHeap.Add(val);
                        runningMedian = lHeap.Peek();
                    }
                    else
                    {
                        rHeap.Add(val);
                        runningMedian = rHeap.Peek();
                    }
                }
                else if (lHeap.Count > rHeap.Count)
                {
                    if (val < runningMedian)
                    {
                        rHeap.Add(lHeap.Delete());
                        lHeap.Add(val);
                    }
                    else
                    {
                        rHeap.Add(val);
                    }

                    runningMedian = (lHeap.Peek() + rHeap.Peek()) / 2.0;
                }
                else
                {
                    if (val < runningMedian)
                    {
                        lHeap.Add(val);
                    }
                    else
                    {
                        lHeap.Add(rHeap.Delete());
                        rHeap.Add(val);
                    }

                    runningMedian = (lHeap.Peek() + rHeap.Peek()) / 2.0;
                }
            }
        }
예제 #8
0
 public void Append01()
 {
     var person1 = new Person { Age = 1 };
     var person2 = new Person { Age = 1 };
     var minheap = new MinHeap<Person, int>(2, x => x.Age);
     minheap.Append(person1);
     minheap.Append(person2);
     foreach (var x in minheap) { break; }
     Assert.AreEqual(person1, minheap.Peek());
     Assert.AreNotEqual(person2, minheap.Peek());
 }
        // b -> starting amount of fuel
        // k -> tank capacity
        public int CheapestFuelCost(int b, int k, int d, int[] distance, int[] price)
        {
            var heap   = new MinHeap();
            var fuel   = b;
            var pos    = 0;
            var result = 0;
            var n      = distance.Length;

            for (var i = 0; i < n; ++i)
            {
                fuel -= distance[i] - pos;

                while (fuel < 0 && heap.Count > 0)
                {
                    var top   = heap.Peek();
                    var quant = Math.Min(top.LeftToRefuel, -fuel);
                    result           += quant * top.Price;
                    top.LeftToRefuel -= quant;
                    if (top.LeftToRefuel == 0)
                    {
                        heap.Pop();
                    }
                    fuel += quant;
                }

                if (fuel < 0)
                {
                    return(-1);
                }
                heap.Add(new HeapNode(price[i], k - fuel));
                pos = distance[i];
            }

            fuel -= d - pos;
            while (fuel < 0 && heap.Count > 0)
            {
                var top   = heap.Peek();
                var quant = Math.Min(top.LeftToRefuel, -fuel);
                result           += quant * top.Price;
                top.LeftToRefuel -= quant;
                if (top.LeftToRefuel == 0)
                {
                    heap.Pop();
                }
                fuel += quant;
            }

            if (fuel < 0)
            {
                return(-1);
            }
            return(result);
        }
예제 #10
0
        public void AddEmptyRemove()
        {
            var heap = new MinHeap();

            heap.Add(10);
            Assert.AreEqual(10, heap.Peek());

            var res = heap.Pop();

            Assert.AreEqual(10, res);
            heap.Add(20);
            Assert.AreEqual(20, heap.Peek());
        }
예제 #11
0
        public int Add(int val)
        {
            if (_minHeap.IsEmpty() || _minHeap.Peek() <= val)
            {
                _minHeap.Insert(val);

                if (_minHeap.Size() > _k)
                {
                    _minHeap.Poll();
                }
            }

            return(_minHeap.Peek());
        }
예제 #12
0
        public void Peek01()
        {
            var minheap = new MinHeap <int>(2);

            Assert.Throws <InvalidOperationException>(() => { minheap.Peek(); });
            minheap.Insert(0);
            Assert.AreEqual(0, minheap.Peek());

            var maxheap = new MaxHeap <int>(2);

            Assert.Throws <InvalidOperationException>(() => { maxheap.Peek(); });
            maxheap.Insert(0);
            Assert.AreEqual(0, maxheap.Peek());
        }
예제 #13
0
    public double FindMedian()
    {
        if (maxH.GetSize() == minH.GetSize())   // When we have the same ammount we took one from each side
        {
            return((double)(maxH.Peek() + minH.Peek()) / 2);
        }

        if (maxH.GetSize() > minH.GetSize())    // If left side has more numbers
        {
            return((double)maxH.Peek());
        }

        return(minH.Peek()); // Right side has more numbers
    }
예제 #14
0
        public void Peek()
        {
            Heap <int> h = new MinHeap <int>();

            h.Add(4);
            Assert.AreEqual(h.Peek(), 4);
            h.Add(5);
            Assert.AreEqual(h.Peek(), 4);
            h.Add(3);
            Assert.AreEqual(h.Peek(), 3);
            h.Add(1);
            Assert.AreEqual(h.Peek(), 1);
            h.Add(2);
            Assert.AreEqual(h.Peek(), 1);
        }
예제 #15
0
        //https://www.programcreek.com/2014/05/leetcode-meeting-rooms-ii-java/
        // O (N Log N) ()
        // Space : O(N)
        public int MinMeetingRooms(int[][] meetings)
        {
            var sortedMeetings = meetings.OrderBy(x => x[0]);

            var minHeap = new MinHeap();

            int count = 0;

            foreach (var interval in meetings)
            {
                var start = interval[0];
                var end   = interval[1];

                if (minHeap.IsEmpty())
                {
                    count++;
                    minHeap.Insert(end);
                }
                else
                {
                    if (start >= minHeap.Peek())
                    {
                        minHeap.Poll();
                    }
                    else
                    {
                        count++;
                    }
                    minHeap.Insert(end);
                }
            }

            return(count);
        }
예제 #16
0
    public int[][] KClosest(int[][] points, int k)
    {
        var minHeap = new MinHeap <int[]>();

        foreach (var point in points)
        {
            var distanceSquared = point[0] * point[0] + point[1] * point[1];

            if (minHeap.Count == k)
            {
                if (minHeap.Peek().Priority < -distanceSquared)
                {
                    minHeap.Pop();
                    minHeap.Push(-distanceSquared, point);
                }
            }
            else
            {
                minHeap.Push(-distanceSquared, point);
            }
        }

        var result = new int[k][];

        while (k > 0)
        {
            result[k - 1] = minHeap.Pop().Data;
            k--;
        }

        return(result);
    }
예제 #17
0
    public int MaxEvents(int[][] events)
    {
        Array.Sort(events, delegate(int[] a, int[] b) {
            if (a[0] == b[0])
            {
                return(a[1] - b[1]);
            }

            return(a[0] - b[0]);
        });
        var heap = new MinHeap();
        int i = 0, count = 0;

        for (var d = 1; d <= 100000; d++)
        {
            while (!heap.IsEmpty() && heap.Peek() < d)
            {
                heap.RemoveMin();
            }

            while (i < events.Length && events[i][0] == d)
            {
                heap.insert(events[i][1]);
                i++;
            }

            if (!heap.IsEmpty())
            {
                heap.RemoveMin();
                count++;
            }
        }

        return(count);
    }
예제 #18
0
 public void AdvanceTime(TimeSpan delta)
 {
     _timeNow += delta.Ticks;
     while (_heap.Count > 0 && _heap.Peek().EndTime <= _timeNow)
     {
         ScheduleEvent scheduleEvent = _heap.ExtractMin();
         _lookup.Remove(scheduleEvent.Id);
         if (!scheduleEvent.Cancelled)
         {
             scheduleEvent.Callback(scheduleEvent.Id, scheduleEvent.State);
             if (!scheduleEvent.Cancelled)
             {
                 scheduleEvent.Cancelled = !scheduleEvent.Repeat;
                 if (scheduleEvent.Repeat)
                 {
                     _repeat.Add(scheduleEvent);
                 }
             }
         }
         if (scheduleEvent.Cancelled)
         {
             _pool.Release(scheduleEvent);
         }
     }
     _repeat.ForEach(delegate(ScheduleEvent s)
     {
         s.StartTime = _timeNow;
         _heap.Add(s);
         _lookup.Add(s.Id, s);
     });
     _repeat.Clear();
 }
예제 #19
0
        //SOLUTION FOR LEETCODE QUESTION:
        //253 - MEETING ROOMS II - Given an array of meeting time intervals intervals where intervals[i] = [starti, endi],
        //return the minimum number of conference rooms required.
        //*****DIFFICULTY - MEDIUM*****


        /// <summary>
        /// Method the returns minimum number of meeting rooms needed given an array of meeting intervals
        /// </summary>
        /// <param name="intervals"></param>
        /// <returns>Number of meeting rooms</returns>
        public int MinMeetingRooms(int[][] intervals)
        {
            //Sort intervals by starting time
            Array.Sort(intervals, (item1, item2) => { return(item1[0].CompareTo(item2[0])); });

            //Invoking MiniHeap class
            var minHeap = new MinHeap(intervals.Length);

            //Add the end time of the first interval to the MinHeap
            minHeap.Add(intervals[0][1]);

            //For each other interval, check if the start time is less than the current min on heap
            for (int i = 1; i < intervals.Length; i++)
            {
                //If true add the end of current interval to MinHeap
                if (intervals[i][0] >= minHeap.Peek())
                {
                    minHeap.Pop();
                }

                //If false, pop the min and add the current end time to heap
                minHeap.Add(intervals[i][1]);
            }

            //The number of elements left in the MinHeap will tell us the number of rooms needed
            return(minHeap.Count());
        }
예제 #20
0
        private List <double> SlidingWindowMedian(double[] input, int window)
        {
            if (window < 2 || window > input.Length)
            {
                throw new ArgumentException();
            }

            var result = new List <double>();

            var maxHeap = new MaxHeap <double>();
            var minHeap = new MinHeap <double>();

            maxHeap.Add(Math.Min(input[0], input[1]));
            minHeap.Add(Math.Max(input[0], input[1]));
            var currentMedian = (maxHeap.Peek() + minHeap.Peek()) / 2;
            var index         = 2;

            while (index < window)
            {
                currentMedian = FindMedian(maxHeap, minHeap, currentMedian, input, index, window);
                index++;
            }
            result.Add(currentMedian);
            for (int i = index; i < input.Length; i++)
            {
                currentMedian = FindMedian(maxHeap, minHeap, currentMedian, input, i, window);
                result.Add(currentMedian);
            }

            return(result);
        }
예제 #21
0
        public int Solve(int k, int[] cookies)
        {
            MinHeap <int> minHeap = new MinHeap <int>(cookies);

            int count = 0;

            while (minHeap.Size > 0)
            {
                if (minHeap.Peek() > k)
                {
                    return(count);
                }

                if (minHeap.Size == 1)
                {
                    break;
                }

                var first  = minHeap.Dequeue();
                var second = minHeap.Dequeue();

                var result = first + (2 * second);
                count++;

                minHeap.Add(result);
            }

            return(-1);
        }
예제 #22
0
        public void Update(float deviceTicks, UpdateEventArgs updateEventArgs)
        {
            _elapsedDeviceTicks += deviceTicks;

            while (!_queue.IsEmpty && _queue.PeekPriority() < _elapsedDeviceTicks)
            {
                var entry = _queue.Peek();

                // update event args with info local to the task
                updateEventArgs.Ticks = _elapsedDeviceTicks - entry.EnqueueTicks;

                // run the task
                var nextTicks = entry.Task.Update(updateEventArgs);

                // see if Updatable wants to be scheduled again
                if (nextTicks > 0)
                {
                    entry.EnqueueTicks = _elapsedDeviceTicks;
                    entry.DequeueTicks = _elapsedDeviceTicks + nextTicks;

                    _queue.Increase(entry.DequeueTicks);
                }
                else
                {
                    _queue.Extract(out _);

                    OnDeregistered?.Invoke(this, entry.Task);
                }
            }
        }
예제 #23
0
파일: TopK.cs 프로젝트: susingh/questions
        private static void PrintTopK(Stream ip, int k, int magicNumber)
        {
            MinHeap <int> heap = new MinHeap <int>();
            int           val;

            while ((val = ip.Next()) != -1)
            {
                if (val == magicNumber)
                {
                    // print the heap
                    continue;
                }

                if (heap.Count == k)
                {
                    if (heap.Peek() < val)
                    {
                        heap.Delete();
                        heap.Add(val);
                    }
                }
                else
                {
                    heap.Add(val);
                }
            }
        }
예제 #24
0
        public void PeekWithoutAdd()
        {
            // Arrange
            var minHeap = new MinHeap <int>();

            Assert.Throws <InvalidOperationException>(() => minHeap.Peek());
        }
예제 #25
0
        /// <summary>
        /// we can use a binary tree to represent prefix free code where 0 means go to the left child and 1 means go to the right child.
        /// Let c.freq denote the frequency of c in the file and let dt(c) denote the depth of c's leaf in the tree.
        /// The number of bits required to encode a file is
        /// sum(c.freq*dt(c))
        ///
        ///
        /// this runs at O(nlgn)
        /// </summary>
        public static Character <T> Build(List <Tuple <T, double> > characters)
        {
            if (characters == null || characters.Count <= 0)
            {
                throw new ArgumentNullException("argument cann't be null or empty");
            }

            int n = characters.Count;

            Character <T>[] arrs = new Character <T> [n];
            //build a min priority queue using minheap
            for (int i = 0; i < n; i++)
            {
                arrs[i] = new Character <T>(characters[i].Item1, characters[i].Item2);
            }

            MinHeap <Character <T> > heap = MinHeap <Character <T> > .BuildMinHeap(arrs);

            for (int i = 0; i < n - 1; i++)
            {
                Character <T> combine = new Character <T>();
                Character <T> left    = heap.Pop();
                Character <T> right   = heap.Pop();
                combine.Left  = left;
                combine.Right = right;
                combine.Freq  = left.Freq + right.Freq;
                heap.Insert(combine);
            }

            return(heap.Peek());
        }
        public void TestPeek()
        {
            int[]         heapArr = { 1, 2, 3, 4, 5, 6 };
            MinHeap <int> pq      = new MinHeap <int>(heapArr);

            Assert.AreEqual(1, pq.Peek());
        }
예제 #27
0
    private void chekNaborsViablity(Ground_Tile lookTile, int[] lookLocation)
    {
        int newG = moveCost;

        //cheking to see if the tile is pathable or if it is in the closed list
        if (lookTile.pathable == true && !closedList.ContainsKey(lookLocation[0] * Board.board.GetLength(1) + lookLocation[1]))
        {
            //Debug.Log("neighbor "+ i +" "+j +" is pathable and not in closed list");
            //setting its G equal to the cost of its position from the curent point added to the curent points G
            newG += curentTileObj.G;
            //cheking if the new tile is in the oppen list
            if (oppenList.contains(lookTile))
            {
                //Debug.Log("" + lookTile.tileY + " " + lookTile.tileX + " is in open list");
                //check to see if its g is smaller or greater then the curent one
                if (lookTile.G < oppenList.Peek(lookTile).G)
                {
                    int heapIndexOfLook = oppenList.PeekL(lookTile);
                    //change the G value and Parent
                    oppenList.changeValuesAt(heapIndexOfLook, newG, curentTileObj);
                }
            }
            else
            {
                //Debug.Log(i + " " + j + " is new");
                //setting the tiles values and puting it in the oppen list
                lookTile.updateValues(newG);
                lookTile.parent = curentTileObj;
                oppenList.Insert(lookTile);
            }
        }
    }
예제 #28
0
        public void DefaultConstructorMinHeap()
        {
            var min = new MinHeap <int>();

            min.Push(1);
            min.Push(2);
            min.Push(3);
            min.Push(4);
            min.Push(5);

            Assert.IsTrue(min.Peek() == 1);
            var val = min.Pop();

            Assert.IsTrue(val == 1);
            Assert.IsTrue(min.Peek() == 2);
        }
예제 #29
0
        public int LargestSumAfterKNegations(int[] A, int K)
        {
            var minheap = new MinHeap <int>();
            int sum     = 0;

            foreach (var num in A)
            {
                sum += num;
                minheap.Add(num);
            }

            int counter = 0;

            while (counter < K)
            {
                if (minheap.Peek() <= 0)
                {
                    var newVal = Math.Abs(minheap.Poll());
                    sum += newVal * 2;
                    minheap.Add(newVal);
                }
                else
                {
                    var newVal = minheap.Poll();
                    sum -= newVal * 2;
                    minheap.Add(-newVal);
                }
                ++counter;
            }
            return(sum);
        }
예제 #30
0
        public void TestHeapifyUpAddOne()
        {
            var integerHeap = new MinHeap <int>();

            integerHeap.Add(13);
            Assert.AreEqual(13, integerHeap.Peek());
        }
예제 #31
0
        /*
         *  Meeting Rooms II
         *  Given an array of meeting time intervals consisting of start and
         *  end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum
         *  number of conference rooms required.
         *
         *  Example 1:
         *
         *  Input: [[0, 30],[5, 10],[15, 20]]
         *  Output: 2
         */

        public static int MinMeetingRooms(int[][] intervals)
        {
            // TC (1, 10), (2, 7), (3, 19), (8, 12), (10, 20), (11, 30)

            // If there is no meeting to schedule then no room needs to be allocated.
            if (intervals == null || !intervals.Any())
            {
                return(0);
            }

            // Sort the meetings in increasing order of their start time.
            Array.Sort(intervals, new StartTimeComparer());

            var availableRoomsHeap = new MinHeap <int>();

            // Add the first meeting. We have to give a new room to the first meeting.
            availableRoomsHeap.Push(intervals[0][1]);

            for (var i = 1; i < intervals.Length; i++)
            {
                // If the room due to free up the earliest is free, assign that room to this meeting.
                if (availableRoomsHeap.Peek() <= intervals[i][0])
                {
                    availableRoomsHeap.Pop();
                }

                // If a new room is to be assigned, then also we add to the heap,
                // If an old room is allocated, then also we have to add to the heap with updated end time.
                availableRoomsHeap.Push(intervals[i][1]);
            }

            // The size of the heap tells us the minimum rooms required for all the meetings.
            return(availableRoomsHeap.Count());
        }
예제 #32
0
        public void Displace01()
        {
            var minheap = new MinHeap<int>(2);
            Assert.AreEqual(0, minheap.Count());
            minheap.Insert(5);
            minheap.Insert(4);
            Assert.AreEqual(4, minheap.Displace(6));
            Assert.AreEqual(2, minheap.Count());
            Assert.AreEqual(5, minheap.Peek());

            var maxheap = new MaxHeap<int>(2);
            Assert.AreEqual(0, maxheap.Count());
            maxheap.Insert(3);
            maxheap.Insert(4);
            Assert.AreEqual(4, maxheap.Displace(2));
            Assert.AreEqual(2, maxheap.Count());
            Assert.AreEqual(3, maxheap.Peek());
        }
예제 #33
0
        public void Peek01()
        {
            var minheap = new MinHeap<int>(2);
            Assert.Throws<InvalidOperationException>(() => { minheap.Peek(); });
            minheap.Insert(0);
            Assert.AreEqual(0, minheap.Peek());

            var maxheap = new MaxHeap<int>(2);
            Assert.Throws<InvalidOperationException>(() => { maxheap.Peek(); });
            maxheap.Insert(0);
            Assert.AreEqual(0, maxheap.Peek());
        }
예제 #34
0
        /// <summary>
        /// Pops elements off heap and validates elements in decreasing order.
        /// </summary>
        /// <param name="integerMinHeap">Integer MinHeap</param>
        /// <returns>true if sorted</returns>
        public bool ValidateIntMinHeapSort(MinHeap<int> integerMinHeap)
        {
            while (integerMinHeap.Size > 0)
            {
                int lower = integerMinHeap.Pop();

                if (lower > integerMinHeap.Peek())
                    return false;
            }

            return true;
        }