Huffman Build
Huffman Build
Build a Huffman code table from symbol frequencies.
Types
type Code struct {
Bits uint32 // code bits stored in the low bits
Len uint8 // number of valid bits
}
func BuildHuffman(freqs []int) []Code
Behavior
freqs[i]is the frequency of symboli.- Return a
codesslice of the same length. - For
freqs[i] == 0, the code length must be0. - If exactly one symbol has non-zero frequency, assign it code length
1with bits0.
Tie-breaking (determinism)
When merging nodes with equal frequency, break ties by lower minimum symbol id in the subtree. For internal nodes, the minimum symbol id is the minimum of its children. The left child is the one that wins the tie-break.
Notes
- Use
0for left edges and1for right edges. Bitsstores the code in the lowestLenbits (MSB-first when writing).
Run tests to see results
No issues detected