示例#1
0
        /// <summary>
        /// Sort an array that has an out-of-order element atmost k distance away from its correct position.
        /// </summary>
        /// <param name="A">Array</param>
        /// <param name="k">k distance</param>
        /// <returns></returns>
        public static int[] SortAlmostSortedArray(int[] A, int k)
        {
            int i    = 0;
            var heap = new MyHeap <int>(k + 1, new HeapItemComparer <int>());

            while (i <= k)
            {
                heap.Insert(A[i++]);
            }

            for (int j = 0; j < A.Length; j++)
            {
                A[j] = heap.Remove();
                if (i < A.Length)
                {
                    heap.Insert(A[i++]);
                }
            }

            return(A);
        }
示例#2
0
        public static Planet[] Get_K_ClosestPlanetsFromEarth(int k, StreamReader sr)
        {
            var heap = new MyHeap <Planet>(k, new HeapItemComparer <Planet>(true));

            while (heap.Count() < k)
            {
                var p = GetNextPlanet(sr);
                if (p == null)
                {
                    break;
                }

                heap.Insert(p);
            }

            while (!sr.EndOfStream)
            {
                var p = GetNextPlanet(sr);
                if (p == null)
                {
                    break;
                }

                var currentMaxFromHeap = heap.Peek();
                // if planet p has EarthDistance lesser than the MaxDistancePlanet from heap,
                // we should remove the MaxDistancePlanet (root) and add p.
                if (p.CompareTo(currentMaxFromHeap) < 0)
                {
                    var r = heap.Remove();
                    Console.WriteLine($"Removed Planet = {r}");
                    heap.Insert(p);
                    Console.WriteLine($"Inserted Planet = {p}");
                }
            }

            return(heap.GetData());
        }