Huffman coding
how it works
The idea on the watch page's first example, abracadabra, then the whole method, step by step.
Abracadabra has 11 letters but only 5 different ones: a 5 times, b and r twice, c and d once. A code gives each letter a string of 0s and 1s. 2 bits make only 4 strings, 00, 01, 10 and 11, too few for 5 letters. So give every letter 3 bits, and the word takes 33. Give the common letters short codes, and it takes fewer. Line the letters up lightest first, two of one weight in letter order: c, d, b, r, a. Take the two lightest and join them into one tree, weighing both. Repeat until one tree is left. The table below makes each join. Read each code from the top of the tree down: 0 for a join's first branch, 1 for its second. a is 0, b 110, c 100, d 101, r 111. No code begins another, which books call a prefix code. So the bits read back with no gaps: 01101110 cuts into 0, 110, 111 and 0, abra. The word takes 23 bits, not 33. Each join weighs at least the one before, as question 3 shows, so a second queue keeps the joins in order. The two lightest are always at the two queues' fronts; the drawing reads the two as one row. Lining the letters up is a sort, the watch page's merge sort, the earlier letter first on a tie: 1 + 1, then 2, then 4, so 8 comparisons. Then 4 joins. This page counts the comparisons. The code below does the same with Python's own sort.
| join | takes | weighs |
|---|---|---|
| J1 | c 1 and d 1 | 2 |
| J2 | b 2 and r 2 | 4 |
| J3 | J1 2 and J2 4 | 6 |
| J4 | a 5 and J3 6 | 11 |
| letter | times | code | bits |
|---|---|---|---|
| a | 5 | 0 | 5 |
| b | 2 | 110 | 6 |
| c | 1 | 100 | 3 |
| d | 1 | 101 | 3 |
| r | 2 | 111 | 6 |
| all | 11 | 23 |
step 1 of 11
Count each letter of abracadabra: a 5, b 2, c 1, d 1 and r 2.
what it remembers to know where it is
- trees in the queue
- not yet
Where it says not yet, nothing is held there at that moment.
step 2 of 11
Line the letters up lightest first, a tie in letter order: c 1, d 1, b 2, r 2 and a 5.
what it remembers to know where it is
- trees in the queue
- 5
step 4 of 11
Join c and d under a new place, J1, weighing 2, both together, c on the left for 0 and d on the right for 1. Each join weighs at least as much as the one before it, so J1 goes behind any joins already in the queue.
what it remembers to know where it is
- trees in the queue
- 4
step 6 of 11
Join b and r under a new place, J2, weighing 4, both together, b on the left for 0 and r on the right for 1. Each join weighs at least as much as the one before it, so J2 goes behind any joins already in the queue.
what it remembers to know where it is
- trees in the queue
- 3
step 8 of 11
Join J1 and J2 under a new place, J3, weighing 6, both together, J1 on the left for 0 and J2 on the right for 1. Each join weighs at least as much as the one before it, so J3 goes behind any joins already in the queue.
what it remembers to know where it is
- trees in the queue
- 2
step 10 of 11
Join a and J3 under a new place, J4, weighing 11, both together, a on the left for 0 and J3 on the right for 1. Each join weighs at least as much as the one before it, so J4 goes behind any joins already in the queue.
what it remembers to know where it is
- trees in the queue
- 1
step 11 of 11
Done: the codes are a 0, b 110, c 100, d 101 and r 111. The text takes 23 bits this way, against 33 if every letter had a code of the same length.
what it remembers to know where it is
- trees in the queue
- 1
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- count each letter, and line the letters up lightest firstPython lines 10, 11, 12, 13 and 14
- while more than one tree is left in the queuePython line 23
- take the two lightest, at the front of the queuePython lines 18, 19, 20, 21 and 24
- join them under a new place weighing both, back in the queue by its weight: 0 to the left, 1 to the rightPython lines 25, 26 and 27
- each letter's code is the way down to it from the top: 0 for each step left, 1 for each step rightPython lines 28, 29, 30, 31, 32, 33, 34, 35, 36 and 37
the same in Python
The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.
from collections import deque
def huffman_coding(text):
"""Give each letter of text a code of 0s and 1s, the fewest bits in all.
text is a word with two or more different letters. Returns a dict from
each letter to its code; no letter's code begins another's.
"""
weight = {}
for letter in text: # count each letter
weight[letter] = weight.get(letter, 0) + 1
# line the letters up lightest first, two of one weight in letter order
letters = deque(sorted(weight, key=lambda x: (weight[x], x)))
joins = deque() # each join is at least as heavy as the last, so this stays in order too
branches = {} # each join's two branches, the first taken on the left
def take(): # the lighter front of the two queues, the letter on a tie
if not joins or (letters and weight[letters[0]] <= weight[joins[0]]):
return letters.popleft()
return joins.popleft()
while len(letters) + len(joins) > 1: # more than one tree left
a, b = take(), take() # the two lightest
join = len(branches) + 1 # a join's name is the order it was made in
weight[join], branches[join] = weight[a] + weight[b], (a, b)
joins.append(join) # back in the queue by its weight
codes = {}
stack = [(take(), "")] # from the top down: 0 to the left, 1 to the right
while stack:
tree, code = stack.pop()
if tree in branches:
first, second = branches[tree]
stack += [(second, code + "1"), (first, code + "0")]
else:
codes[tree] = code
return codes
how it scales
The plot counts the sort's comparisons lining up different letters weighing 1 to , in two orders. Weights falling in letter order cost the fewest any order costs, and weights in the dearest order the most. Measured from 10 to 1,000.
Each mark across or up is ten times the one before. Both lines climb a little over one mark up for each mark across. The dearest order makes 589 at 100 letters and 8,985 at 1,000, about 15 times. The plot's note reads it further out, from a million to ten million letters: about 12 times. The extra over ten times comes from the log in , which section 4 derives.
comparisons to line the letters up, ten times more at each mark up
, how many different letters the text has, ten times more at each mark to the right
- weights in the dearest ordersolid where measured by running it; dashed where its formula carries it on to ten millionslope 1.1: ten times n, 12 times the work
- weights falling in letter ordersolid where measured by running it; dashed where its formula carries it on to ten million
| comparisons to line the letters up | time | |
|---|---|---|
| 1,000 | 8,985 | about 9 microseconds |
| 100,000 | 1,592,993 | about 1.6 milliseconds |
| 10,000,000 | 226,648,193 | about 227 milliseconds |
The comparisons to line the letters up are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.
make these counts yourself
Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.
"""Count Huffman coding's comparisons yourself, as the plot on this page does.
Run it with Python 3.12 or later. For each size n it builds two words of n
different letters weighing 1 to n: weights falling in letter order, the
fewest comparisons any order costs, and weights in the dearest order, the
most. It prints the comparisons the sort makes lining up the letters, by
count below, the watch page's merge in place of Python's own sorted. The
counts are the same on any computer; only the time differs.
"""
from collections import deque
def huffman_coding(text):
"""Give each letter of text a code of 0s and 1s, the fewest bits in all.
text is a word with two or more different letters. Returns a dict from
each letter to its code; no letter's code begins another's.
"""
weight = {}
for letter in text: # count each letter
weight[letter] = weight.get(letter, 0) + 1
# line the letters up lightest first, two of one weight in letter order
letters = deque(sorted(weight, key=lambda x: (weight[x], x)))
joins = deque() # each join is at least as heavy as the last, so this stays in order too
branches = {} # each join's two branches, the first taken on the left
def take(): # the lighter front of the two queues, the letter on a tie
if not joins or (letters and weight[letters[0]] <= weight[joins[0]]):
return letters.popleft()
return joins.popleft()
while len(letters) + len(joins) > 1: # more than one tree left
a, b = take(), take() # the two lightest
join = len(branches) + 1 # a join's name is the order it was made in
weight[join], branches[join] = weight[a] + weight[b], (a, b)
joins.append(join) # back in the queue by its weight
codes = {}
stack = [(take(), "")] # from the top down: 0 to the left, 1 to the right
while stack:
tree, code = stack.pop()
if tree in branches:
first, second = branches[tree]
stack += [(second, code + "1"), (first, code + "0")]
else:
codes[tree] = code
return codes
def count(text):
"""How many comparisons the watch page's sort makes lining up the
letters: in letter order, runs of 1, 2, 4 and on merged in neighbouring
pairs, the lighter first, and on a tie the earlier letter."""
weight = {}
for letter in text:
weight[letter] = weight.get(letter, 0) + 1
runs = [[(weight[x], x)] for x in sorted(weight)]
compared = 0
while len(runs) > 1:
merged = []
for k in range(0, len(runs) - 1, 2):
left, right = runs[k], runs[k + 1]
run = []
i = j = 0
while i < len(left) and j < len(right):
compared += 1
if right[j] < left[i]:
run.append(right[j])
j += 1
else:
run.append(left[i])
i += 1
merged.append(run + left[i:] + right[j:])
if len(runs) % 2 == 1:
merged.append(runs[-1])
runs = merged
return compared
def letters_of(n):
"""n different letters in letter order: a to z, or past 26 letters from
the Chinese characters on, one plane, so their order is their numbers'."""
return [chr(97 + k) if n <= 26 else chr(0x4E00 + k) for k in range(n)]
def cheapest(n):
"""n letters weighing n down to 1 in letter order: the fewest comparisons."""
return "".join(x * (n - k) for k, x in enumerate(letters_of(n)))
def dearest(n):
"""n letters weighing 1 to n in the dearest order: in every merge, the
two heaviest sit in different runs."""
order = [0] * n
def deal(at, ranks):
if len(ranks) == 1:
order[at] = ranks[0]
return
split = 1
while split * 2 < len(ranks): # the largest power of 2 below the run's length
split *= 2
left, right = [], []
for i, rank in enumerate(reversed(ranks)): # from the heaviest down
if i % 2 == 0 and len(right) < len(ranks) - split:
right.insert(0, rank)
else:
left.insert(0, rank)
deal(at, left)
deal(at + split, right)
deal(0, list(range(1, n + 1)))
return "".join(x * order[k] for k, x in enumerate(letters_of(n)))
if __name__ == "__main__":
print(f"{'n':>6} {'falling':>9} {'dearest':>9}")
for n in (10, 20, 50, 100, 200, 500, 1000):
print(f"{n:>6} {count(cheapest(n)):>9} {count(dearest(n)):>9}")
best, worst and average
Here best and worst say how the weights 1 to are handed to the letters: each letter gets one, and the cases differ only in which letter gets which. Which runs the sort merges depends only on ; where each merge stops, when one run is used up, depends on the weights. The joins never move: on every word. No average is worked out.
A case is one order of the weights. A bound says how fast that order's cost grows as letters are added.
The counts are in the grid below. A count is often made of pieces that grow at different speeds, and the fastest-growing piece swamps the rest. In the dearest order at 1,000 letters, is 10,000, less 16 waiting and 999 for the merges: 8,985. The 10,000 is most of it. So how a cost grows is what tells one method from another, and the bounds keep just that.
| bestweights falling in letter order | worstweights in the dearest order | |
|---|---|---|
| comparisons to line the letters up | , the right runs | |
| joins | ||
| how the comparisons to line the letters up grow in each case | ||
| tight, | ||
| ceiling, | ||
| floor, | ||
extra memory: The letters and their weights, a queue of joins, and each join's two branches.
Extra memory is the room it needs on top of the input itself, while it runs.
| word | weights in letter order | comparisons | joins |
|---|---|---|---|
| aaaabbbccd | 4, 3, 2, 1 | 4 | 3 |
| abbcccdddd | 1, 2, 3, 4 | 4 | 3 |
| abbbccdddd | 1, 3, 2, 4 | 5 | 3 |
where the formula comes from
Questions 1 and 2 count the comparisons, the plot's two lines. Question 3 counts the joins, and question 4 shows why the codes spend the fewest bits.
the move: how the sort goes
the line:5 numbers stand for 5 letters' weights, falling. Round 2's merge, 4, 5 with 2, 3, compares 2 with 4, then 3 with 4. Then the right run is used up, and 4 and 5 follow with no comparison. round run length merges comparisons 1 1 2 2 2 2 1 2 3 4 1 1 all 4 5 Five letters, weights falling. In rounds 1 and 2 the last run waits. why it is allowed: The watch page's sort is merge sort, from the bottom up. Each letter starts as a run of 1, in letter order. Each round merges neighbouring runs, comparing their front letters and taking the lighter. A last run with no partner waits. Every run is 1, 2, 4 and on long, except perhaps a round's last, which is shorter. A last run is a right run or waits, so a right run is never the longer. Which runs meet depends only on , never on the weights.
the move: a merge's least
the line:why it is allowed: A merge stops when one run is used up, and each letter of that run needed one comparison to leave it. By line 1, the right run is never the longer. So whichever run is used up holds at least the right run's length. For 4, 5 with 2, 3, at least 2 comparisons.
guess it, thenthe move: weights falling, the right run is used up first
the line:run length right runs comparisons 1 5 of 1 5 2 2 of 2 4 4 1 of 4 4 8 1 of 2 2 all 15 Ten letters, weights falling. At run length 2 the last run waits, and at 4 the last 2 letters wait. At 8 the right run holds only those 2. why it is allowed: With weights falling, each right run's letters weigh less than the left run's beside it. So the right run is used up first, one comparison each, the least line 2 allows. adds up the right runs in the round of runs of 1, of runs of 2, and so on. For 5, 2 + 2 + 1.
guess it, thenthe move: a ceiling
the line:Top, numbers, each double the last; bottom, their logs, each 1 more. 5 lies between 4 and 8, so its log, about 2.3, rounds up to 3. 10 lies between 8 and 16, so its log, about 3.3, rounds up to 4. why it is allowed: In a pair the right run is never the longer, so a round's right runs hold at most half the letters, . Run lengths double until one run holds all , so there are rounds. Multiply the two. For 5, half of 5 times 3 rounds is 7.5, and is 5.
guess it, thenthe move: a simpler ceiling
the line:why it is allowed: Rounding up adds less than 1, and when is 2 or more, is at least 1. So is at most twice , and times twice is . For 5, is 5, at most 11.6.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 5, with the fixed multiple 1.
guess it, thenthe move: a floor
the line:run length full pairs hold their right runs a quarter of 5 1 4 2 1.25 2 4 2 1.25 Five letters. In each round with a full pair, the full pairs hold 4 of the 5, at least half, and their right runs 2, at least a quarter. 2 such rounds, so at least 2.5. why it is allowed: Take a round whose runs are long, with at most , so at least one full pair of runs fits, letters. What is left over is fewer than , so the full pairs hold at least half the letters, and their right runs at least a quarter, . Such rounds have as 1, 2, 4 and on, while is at most , so there are of them. By line 3, adds up every round's right runs, so multiply the two. For 5, rounds of 1 and 2, so at least 2.5.
guess it, thenthe move: the rounded log against the exact one
the line:why it is allowed: Call line 7's rounded-down log . Rounding down took off less than 1, so is below . From 2 up is at least 1, so is at most . For 5, is 2, and the log of 5, about 2.3, is below 3, and 3 is at most 4.
guess it, thenthe move: drop the rounding
the line:why it is allowed: By line 8, is at least half of . Put that into line 7, and times half of is . For 5, is 5, at least 1.45.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 9, with the fixed multiple an eighth.
guess it, thenthe move: both together
the line:why it is allowed: Lines 6 and 10 bound by the same growth.
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
the move: a merge's most
the line:why it is allowed: Each comparison sends one letter into the new run. When one run is used up, the other still holds at least one letter, which follows with no comparison.
the move: the dearest order
the line:run of weights left run gets right run gets 1, 2, 3, 4, 5, 6 1, 2, 3, 5 4, 6 1, 2, 3, 5 1, 3 2, 5 1, 3 1 3 2, 5 2 5 4, 6 4 6 Dealing 6 weights. 6 goes right, 5 left, 4 right, and a right run of 2 is full, so 1 to 3 go left. Each left run comes before its right run, so the order is 1, 3, 2, 5, 4, 6. why it is allowed: By question 1's line 1, the left run of a merge is a full run, 1, 2, 4 or on long. The right run holds at least 1 letter and no more than the left. So a run of letters splits into the largest power of 2 below and the rest. Deal the weights out from the heaviest down, one to the right run and one to the left in turn, until the right run is full. The rest go left. Then deal each run the same way.
guess it, thenthe move: each merge, line 1's most
the line:why it is allowed: By line 2, the run without the heaviest ends with the second heaviest. Every other letter is lighter and goes in first. When the second heaviest goes in, that run is used up and only the heaviest is left.
guess it, thenthe move: each merge, one less than it holds
the line:merge merged comparisons 1 with 3 2 1 2 with 5 2 1 4 with 6 2 1 1, 3 with 2, 5 4 3 1, 2, 3, 5 with 4, 6 6 5 all 16 11 The dearest order of 6 weights: 1, 3, 2, 5, 4, 6. In round 2 the run 4, 6 waits. 16 merged, 5 merges, 11 comparisons. why it is allowed: By line 3, each merge compares one less than it holds. Add that up over every merge.
guess it, thenthe move: the letters merged
the line:why it is allowed: Each of the rounds, as in question 1's line 4, merges every letter except a run that waits. adds up the letters that wait. For 6, 18 less 2, which is 16.
guess it, thenthe move: the merges
the line:why it is allowed: Each merge makes one run fewer, from runs to 1. For 6, 5.
guess it, thenthe move: put them together
the line:why it is allowed: Lines 4, 5 and 6 together. By line 1, no order makes more. For 6, 16 less 5, which is 11.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 7, dropping the and the it takes away, as neither is below 0. For 6, 11 is at most 18.
guess it, thenthe move: a simpler ceiling
the line:why it is allowed: As in question 1's line 5, is at most twice . For 6, whose log is about 2.58, at most 31.0.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 9, with the fixed multiple 2.
guess it, thenthe move: a floor
the line:why it is allowed: By question 1's lines 2 and 3, every merge compares at least its right run, whatever the weights, and adds up the right runs. So is at least , and question 1's line 7 gives this floor. For 6, 11 is at least 3.
guess it, thenthe move: drop the rounding
the line:why it is allowed: As in question 1's lines 8 and 9. For 6, at least 1.94.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 12, with the fixed multiple an eighth.
guess it, thenthe move: both together
the line:why it is allowed: Lines 10 and 13 bound by the same growth.
guess it, then
try it with a small : at , line 7 gives , which you can work out by hand
the move: one tree fewer each join
the line:after trees left the start 5 J1 4 J2 3 J3 2 J4 1 Abracadabra's 5 letters, joined in 4 steps. why it is allowed: Each letter starts as a tree of its own, trees. Each join takes two trees and gives back one, until one is left. Whatever the weights. For 5, 4.
the move: each join at least the last
the line:why it is allowed: A join takes the two lightest, so every tree left, and the join itself, weighs at least the heavier of them. The next join takes two such trees, so it weighs at least twice the heavier. The last weighed the heavier plus the lighter, no more. Abracadabra's weigh 2, 4, 6 and 11.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 1, as is less than .
guess it, thenthe move: read the bound
the line:why it is allowed: By line 3, with the fixed multiple 1.
guess it, thenthe move: a floor
the line:why it is allowed: From 2 up, 1 is at most half of , so is at least half of . For 5, 4 is at least 2.5.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 5, with the fixed multiple a half.
guess it, thenthe move: both together
the line:why it is allowed: Lines 4 and 6 bound by the same growth.
guess it, thenthe move: the sort grows faster
the line:why it is allowed: By question 1's lines 2, 3 and 9, any weights make at least comparisons, and by line 3 the joins are at most . So the comparisons are at least times the joins, a number that grows without end. It is 1 or more from 256 on, as the log of 256 is 8. At 1,000 letters, 999 joins against 4,932 comparisons with weights falling and 8,985 in the dearest order.
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
the move: what a code costs
the line:why it is allowed: A code where no letter's code begins another's is a tree, every letter at the bottom, its code the way down to it. So a code's length is its letter's depth. Tattoo has t 3 times, o twice and a once. The method's code, t 0, a 10 and o 11, spends 3 + 2 + 4, which is 9.
the move: swap a lightest letter deepest
the line:A worse code for tattoo as a tree, a 0 at depth 1, t 10 and o 11 at depth 2. 3 times 2, 1 times 1 and 2 times 2 is 11 bits. letter times code before code after t 3 10 0 a 1 0 10 o 2 11 11 Swapping a and t turns the worse code into the method's code. why it is allowed: Take a code and a letter in one of its deepest places. Swap that letter with one of the lightest letters, whichever the method takes on a tie. The letter that is no lighter moves up, and the lighter one down, each by the same depth.
guess it, thenthe move: in the picture, count the change
the line:The method's code for tattoo, t 0 at depth 1, a 10 and o 11 at depth 2. 9 bits. why it is allowed: In the picture, t, appearing 3 times, moves up 1 and saves 3 bits. a, appearing once, moves down 1 and adds 1. So 2 fewer, in this swap. is 11 and is 9.
guess it, thenthe move: never dearer
the line:why it is allowed: In any swap of line 2, the letter moving up appears at least as often as the one moving down, and both move the same depth. It saves its times that depth; the other adds its own times that depth, no more. So the bits fall or stay. In the picture, 3 saved and 1 added.
guess it, thenthe move: the two lightest at the bottom
the line:why it is allowed: Start from a code of the fewest bits. Each of its joins has two branches, or skipping a lone one would save bits; t 0, a 10 and o 110 spends 11, and o 11 spends 9. So its deepest join holds two letters. Swap the lightest into one branch, as in line 2, then the next lightest into the other. Line 4's reason holds for both: every other letter appears at least as often as either.
guess it, thenthe move: join them, one letter fewer
the line:word codes bits t 3, ao 3 t 0, ao 1 6 t 3, a 1, o 2 t 0, a 10, o 11 9 Tattoo with a and o as one letter, ao, weighing 3. Read down: split, 6 + 3 = 9. Read up: join the pair back, 9 - 3 = 6; this needs a and o paired, which line 5 gives. why it is allowed: Treat the two lightest as one letter weighing both, as the method's first join does, a smaller word. Splitting that letter one level down turns a code for the smaller word into one for the whole, at the pair's weight more. Joining the pair back undoes it. By line 5 some code of the fewest bits pairs them, so the fewest for the whole is the smaller word's fewest plus the pair's weight.
guess it, thenthe move: the method's codes are the fewest
the line:join takes weighs J1 a 1 and o 2 3 J2 t 3 and J1 3 6 Tattoo's joins. Keep J1 as one letter: 2 letters are left, t and J1, 1 bit each, 6 bits. Split it into a and o, and 3 more make 9. why it is allowed: With 2 letters, no code spends less than 1 bit a letter, and the method's 0 and 1 spend exactly that. Each join is line 6's step, one letter fewer. So repeating it from 2 letters up, the method's code spends the fewest bits.
guess it, thenthe move: the bits from the joins
the line:why it is allowed: A letter's depth is the number of joins above it, and each join weighs every appearance below it once. So adding the joins' weights counts each letter's times once for each join above it, its times its depth, the bits of line 1. Tattoo, 3 + 6, which is 9. Abracadabra, 2 + 4 + 6 + 11, which is 23.
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
count it yourself
The watch page's second example, the word abstract: a and t twice, b, c, r and s once. Its weights in letter order make the most comparisons 6 letters can: 6 times 3, less 2 waiting, less 5 merges, which is 11. The sort makes all 11 at step 2. Then each step joins two trees. The last columns are running totals.
| step | what happens | comparisons to line the letters up | joins |
|---|---|---|---|
| 1 | Count each letter of abstract: a 2, b 1, c 1, r 1, s 1 and t 2. | 0 | 0 |
| 2 | Line the letters up lightest first, a tie in letter order: b 1, c 1, r 1, s 1, a 2 and t 2. | 11 | 0 |
| 3 | The two lightest at the front are b, weighing 1, and c, weighing 1. | 11 | 0 |
| 4 | Join b and c under a new place, J1, weighing 2, both together, b on the left for 0 and c on the right for 1. Each join weighs at least as much as the one before it, so J1 goes behind any joins already in the queue. | 11 | 1 |
| 5 | The two lightest at the front are r, weighing 1, and s, weighing 1. | 11 | 1 |
| 6 | Join r and s under a new place, J2, weighing 2, both together, r on the left for 0 and s on the right for 1. Each join weighs at least as much as the one before it, so J2 goes behind any joins already in the queue. | 11 | 2 |
| 7 | The two lightest at the front are a, weighing 2, and t, weighing 2. | 11 | 2 |
| 8 | Join a and t under a new place, J3, weighing 4, both together, a on the left for 0 and t on the right for 1. Each join weighs at least as much as the one before it, so J3 goes behind any joins already in the queue. | 11 | 3 |
| 9 | The two lightest at the front are J1, weighing 2, and J2, weighing 2. | 11 | 3 |
| 10 | Join J1 and J2 under a new place, J4, weighing 4, both together, J1 on the left for 0 and J2 on the right for 1. Each join weighs at least as much as the one before it, so J4 goes behind any joins already in the queue. | 11 | 4 |
| 11 | The two lightest at the front are J3, weighing 4, and J4, weighing 4. | 11 | 4 |
| 12 | Join J3 and J4 under a new place, J5, weighing 8, both together, J3 on the left for 0 and J4 on the right for 1. Each join weighs at least as much as the one before it, so J5 goes behind any joins already in the queue. | 11 | 5 |
| 13 | Done: the codes are a 00, b 100, c 101, r 110, s 111 and t 01. The text takes 20 bits this way, against 24 if every letter had a code of the same length. | 11 | 5 |
In all, 11 comparisons to line the letters up. The formula from section 4, , gives at : the same.
where you meet it
A student found the method in 1951 and published it in 1952. It is inside DEFLATE, which most ZIP files and every PNG picture use.
Huffman's 1952 paper
Robert Fano offered his class at MIT a paper on the best such code in place of the final examination, as the books tell. David Huffman, a student, found in 1951 that the tree is easy to build from the bottom, and published the method in 1952.
source: D. A. Huffman, Proceedings of the IRE 40(9), 1952, pages 1098 to 1101, A method for the construction of minimum-redundancy codes (opens in a new tab) and G. Stix, Scientific American, September 1991, for 1951, and the books' volume three, chapter 37
DEFLATE, in ZIP and PNG
DEFLATE squeezes a file in two steps. First it writes repeats as short notes, then it gives those notes, and the letters between them, Huffman codes. Most ZIP files and every PNG picture use it.
source: RFC 1951 by P. Deutsch, 1996, DEFLATE compressed data format specification version 1.3 (opens in a new tab) and section 10.1 of the W3C's third edition PNG specification (opens in a new tab) and sections 4.1.3 and 4.4.5 of PKWARE's APPNOTE.TXT (opens in a new tab)
The books' shift
The books code a delivery shift of 60 stops, each one of six letters: D 24 times, P 10, A 9, S 8, N 7 and R 2. A fixed code of 3 bits each takes 180 bits. Huffman's takes 141, the fewest of any code where no letter's code begins another's.
source: the books' volume three, chapter 37
what is used instead
When one letter is nearly certain, it still costs at least 1 bit each time. Arithmetic coding, and now asymmetric numeral systems, give no letter a string of its own, and come closer to the least possible, as the books note (volume three, chapter 37).
how it compares
A fixed code gives every letter the same length. Huffman's gives the common letters short codes.
| way | bits for abracadabra |
|---|---|
| a byte a letter | 88 |
| 3 bits a letter | 33 |
| Huffman's code | 23 |