Lab · c16.s04.L1

Huffman coding

Merge the two least probable nodes until one tree remains; the tree gives short codewords to probable symbols.

Question: How do you build the shortest code?

Huffman codingA tree grows from five symbol leaves, a to e, labelled with their probabilities. At each step the two least probable nodes are ringed in gold and joined by a dashed line, and a parent carrying their summed probability appears above them; four merges leave one root. Reading 0 on a left branch and 1 on a right gives the prefix code: probable symbols short codewords, rare ones long. Bars compare average length with entropy and a fixed three-bit code.Huffman coding: merge the two least probable nodesleft branch 0 · right branch 1 · no codeword is the start of anotherMerge treeleafmerged nodepair that merges nextnode just madeSection example — The five-symbol source from the section: 0.25, 0.25, 0.20, 0.15, 0.15.Each merge joins the two least probable nodesinto one parent, and the tree grows upward.a0.25b0.25c0.2d0.15e0.15Two least probabled0.15e0.15+join into one node of probability0.3sum of the two smallestPrefix codesymPcodebitsa0.25—b0.25—c0.2—d0.15—e0.15—Average length, entropy and the fixedthree-bit code appear at the last step.
Re-simulated Re-simulated: data/scripts/c16.s04.L1.py rebuilds the Huffman tree and reproduces the section's 2.300-bit average length and 2.2855-bit entropy. The four source distributions are chosen teaching values, not measurements. The frames trace the four merges for one source at a time and end on the finished tree, the codeword table and the three bars.
Lab controls
Section example

Arrow keys change the source, Home and End go to the first and last; Space plays the merges, Left and Right step back and forward.

Frame 1 of 5: Step 0 of 4Start with five leaves. The two least probable are d (0.15) and e (0.15).

Step 0 of 4. Start with five leaves. The two least probable are d (0.15) and e (0.15).

Keyboard: Space plays or pauses, Left and Right step, Home goes to the first frame, End goes to the last frame.

Text description of this lab

A tree grows from five symbol leaves, a to e, labelled with their probabilities. At each step the two least probable nodes are ringed in gold and joined by a dashed line, and a parent carrying their summed probability appears above them; four merges leave one root. Reading 0 on a left branch and 1 on a right gives the prefix code: probable symbols short codewords, rare ones long. Bars compare average length with entropy and a fixed three-bit code.

Return to the section that hosts this lab

Caption status: re-simulated. Every lab declares one of published, re-simulated, schematic, synthetic or interpolated.