Esempio n. 1
0
        private static void ExtractMax(MaxPriorityQueue priorityQueue)
        {
            int[]      nums = new int[] { 15, 13, 9, 5, 12, 8, 7, 4, 0, 6, 2, 1 };
            Heap <int> heap = new Heap <int>(nums);
            int        max  = priorityQueue.ExtractMax(heap);

            Console.WriteLine($"{string.Join(',', nums)} max is {max}, heap is {string.Join(',', heap.GetHeap())}");
        }
Esempio n. 2
0
        private static List <int> Merge(List <int>[] lists, int k)
        {
            MaxPriorityQueue priorityQueue = new MaxPriorityQueue();
            Heap <int>       heap          = new Heap <int>(k);
            List <int>       merged        = new List <int>();

            List <Queue <int> > queues = new List <Queue <int> >();

            foreach (var list in lists)
            {
                Queue <int> queue = new Queue <int>(list);
                queues.Add(queue);
            }

            foreach (var queue in queues)
            {
                int n = queue.Dequeue();
                priorityQueue.Insert(heap, n);
            }

            int i = 0;

            while (queues.Count > 0)
            {
                if (queues[i].Count == 0)
                {
                    queues.RemoveAt(i);
                    continue;
                }
                int max = priorityQueue.ExtractMax(heap);
                merged.Add(max);
                int n = queues[i].Dequeue();
                priorityQueue.Insert(heap, n);
                i = (++i) % queues.Count;
            }

            while (heap.HeapSize > 0)
            {
                int remain = priorityQueue.ExtractMax(heap);
                merged.Add(remain);
            }

            return(merged);
        }