An In-Depth Look At Huffman Encoding
dreamincode.net
dreamincode.net
http://en.wikipedia.org/wiki/Huffman_coding#Basic_technique
Even though I was writing it in Java, it was a lot of fun. I ended up with something that I could use on the server side, or compiled down to javascript in the client with GWT.
As an aside, the two-queue technique is also more performant, as you can build the tree in O (n) time instead of O (n log n) time.
If you squint just about right, you can probably see the equivalence between sorting plus queues and the tree based techniques. Especially if you use a tree-structured sorting algorithm.
I know what you're thinking: why not transform the tree into an Ahnentafel list and marshall it to a string containing only the alphabet characters in the appropriate slots, and use another chosen character to represent null slots, and write another implementation of the decoder that's driven off of the array? (Edit: Or, better still, transform it to a canonical Huffman codebook)
Yes, of course I could do that — and I actually want to. Alas, I have bigger fish to fry than writing the tree transformation code, the marshaling code, and the additional decoder implementation. So, when it's all said & done, according to the tradeoffs I was willing to make, my clients get to build the tree in O(n). I can tell that you're vexed that it worked out that way, but that's life.
I was just thinking about purely theoretical optima.
That said, you generally have fixed frequencies with a predetermined set of constraints on the data, and you can determine the most common character frequency (or it's already known). I'm not sure how common this is in real-world applications of Huffman coding.
Seeing as you should only be building the tree once though, you're right--you'd be hard-pressed to tell the difference between the two approaches, barring implementation mistakes. Designing an implementation mistake that would cause noticeable differences is an exercise left to the reader.
http://en.wikipedia.org/wiki/Arithmetic_coding
EDIT: Note that in all cases, we assume that the symbol occurrences are independent. LZW outperforms Huffman because it doesn't make any such assumption.
Another thing that's fun to implement is the Burrows-Wheeler transform which is at the heart of bzip2 (and you then need another compressor for the BW-transformed text, but still...)
You can probably view Huffman-coding as a very special case of arithmetic coding.
I'm pretty sure the patents have expired by now, though.