我目前正在尝试编写一个读取文本文件并通过创建 HuffmanTree 对其进行编码的程序。我在优先队列的二叉堆中使用并行数组并跟踪我的霍夫曼树。
我知道从堆中取出两分钟,合并它们,然后将它们插回堆中直到只剩下一个的原理,但是我无法将该逻辑/算法转换为代码。
这是我的 HuffmanEncode 类:
public class HuffmanEncode {
public HuffmanEncode(String in, String out) {
// Implements the Huffman encoding algorithm
// Add private methods and instance variables as needed
int[] freqs = new int[128]; // character counts
char[] chars = new char[128]; //characters
freqs = countFrequencies(in);
HuffmanTree[] trees = new HuffmanTree[128]; //single node trees
for(int i= 0; i < freqs.length; i++) {
chars[i] = (char)i;
trees[i] = new HuffmanTree(chars[i]);
}
BinaryHeap heap = new BinaryHeap(128); // create a binary heap
for(int i = 0; i < 128; i++) {
heap.insert(freqs[i], trees[i]);
}
// STUCK HERE
buildTree(heap);
HuffmanTree root = new HuffmanTree();
// STUCK HERE
}
private void buildTree(BinaryHeap h) {
// grab two smallest
while (h.getSize() > 1) { //repeat until there is only one left
int temp1, temp2;
HuffmanTree t1, t2;
temp1 = h.getMinPriority();
temp2 = h.getMinPriority();
// add their frequency to create new single node tree with char 128
int sum = temp1 + temp2;
HuffmanTree node = new HuffmanTree((char)128);
// insert it back into the heap
h.insert(sum, node);
}
}
慕田峪4524236
天涯尽头无女友
相关分类