public MinHeapNode BuildHuffmanTree(char[] data, int[] freq, int size)
        {
            MinHeapNode left, right, top;
            MinHeap     minHeap = CreateAndBuildMinHeap(data, freq, size);

            while (!IsSizeOne(minHeap))
            {
                // extract two min freq items from min heap
                left  = ExtractMin(minHeap);
                right = ExtractMin(minHeap);

                top       = NewNode('$', left.Freq + right.Freq);
                top.Left  = left;
                top.Right = right;
                InsertMinHeap(minHeap, top);
            }
            return(ExtractMin(minHeap));
        }
Beispiel #2
0
        /// <summary>
        /// Runtime O(n * log(n))
        /// </summary>
        /// <returns>The kth smallest.</returns>
        /// <param name="arr">Arr.</param>
        /// <param name="k">K.</param>
        public int FindKthSmallest(int[] arr, int k)
        {
            // push into a heap
            var minHeap = new MinHeap <int>();

            for (var i = 0; i < arr.Length; i++)
            {
                minHeap.Insert(arr[i]);
            }

            // what is insert run time for a heap - log(n)
            var min = int.MaxValue;

            for (int i = 0; i < k; i++)
            {
                min = minHeap.ExtractMin();
            }

            return(min);
        }
        public void MinHeapify(MinHeap minHeap, int index)
        {
            int smallest = index;
            int left     = 2 * index + 1;
            int right    = 2 * index + 2;

            if (left < minHeap.Size && minHeap.Nodes[left].Freq < minHeap.Nodes[smallest].Freq)
            {
                smallest = left;
            }
            if (right < minHeap.Size && minHeap.Nodes[right].Freq < minHeap.Nodes[smallest].Freq)
            {
                smallest = right;
            }

            if (smallest != index)
            {
                SwapMinHeapNode(minHeap.Nodes, smallest, index);
                MinHeapify(minHeap, smallest);
            }
        }
 public bool IsSizeOne(MinHeap minHeap)
 {
     return(minHeap.Size == 1);
 }