Example #1
0
        public static int[] Sort(int[] arr, int k)
        {
            int[]            result      = new int[arr.Length];
            int              resultIndex = 0;
            BinaryHeap <int> heap        = new BinaryHeap <int>();

            // add k items into heap
            for (int i = 0; i < k && i < arr.Length; ++i)
            {
                heap.Insert(arr [i]);
            }

            // add and remove
            for (int i = k; i < arr.Length; ++i)
            {
                heap.Insert(arr [i]);
                result [resultIndex++] = heap.RemoveRoot();
            }

            // remove remaining
            while (heap.Count > 0)
            {
                result [resultIndex++] = heap.RemoveRoot();
            }

            return(result);
        }
Example #2
0
        public static float[] GetRunningMedians(int[] a)
        {
            float[]          medians = new float[a.Length];
            BinaryHeap <int> maxHeap = new BinaryHeap <int>(new MaxSort());
            BinaryHeap <int> minHeap = new BinaryHeap <int>();

            for (int i = 0; i < a.Length; ++i)
            {
                int val = a [i];
                if (minHeap.Count == 0)
                {
                    minHeap.Insert(val);
                }
                else
                {
                    if (val > minHeap.Peek())
                    {
                        minHeap.Insert(val);
                    }
                    else
                    {
                        maxHeap.Insert(val);
                    }
                }

                if (minHeap.Count > maxHeap.Count + 1)
                {
                    maxHeap.Insert(minHeap.RemoveRoot());
                }
                else if (maxHeap.Count > minHeap.Count)
                {
                    minHeap.Insert(maxHeap.RemoveRoot());
                }

                medians [i] = (minHeap.Count > maxHeap.Count ? (float)minHeap.Peek() : ((float)(maxHeap.Peek() + minHeap.Peek()) / 2f));
            }

            return(medians);
        }