Short answer: Shannon-Fano coding builds a prefix code by sorting symbols by probability and splitting the list into two groups whose total probabilities are as equal as possible. One group gets a leading 0 and the other a leading 1. Each group is split the same way until every group is a single symbol. The code is prefix-free and is not always optimal. Huffman coding builds the optimal prefix code from the bottom up and should be preferred when optimality matters.
What the problem actually asks
A top-down split is an easy picture of a prefix code: every symbol in the left group starts with 0, every symbol in the right group starts with 1, and no code is a prefix of another because the tree leaves are the symbols. The split rule, equalizing weight, tries to spend the next bit on a meaningful cut. It does not try every tree. Huffman’s exchange argument shows that merging the two lightest nodes is the step that optimality requires, and a top-down cut can miss that tree.
A small example is enough to see the gap. Probabilities 0.35, 0.17, 0.17, 0.16, 0.15 can lead a Shannon-Fano split to a code longer than the Huffman code for the same weights. The existence of one such list is the reason the algorithm is not called optimal.
What the algorithm guarantees
The procedure returns a prefix code. Decoding walks the bits from the root and never needs a separator. The average length is at most the entropy plus one, in the same broad family as other prefix codes, and it can be strictly worse than Huffman on the same probabilities. Time is a sort plus a linear number of splits. Extra memory is the tree.
Ties in the split, when several cut positions are equally balanced, produce different codes of possibly different average lengths. A specification has to say which cut it takes. Huffman also has ties, and every Huffman tie is still optimal. A Shannon-Fano tie need not be.
The working steps
- Sort the symbols by nonincreasing probability.
- Find a cut that minimizes the absolute difference between the total probability of the left part and the right part. Assign 0 to the left and 1 to the right, or the reverse, consistently.
- Recurse on each part that contains at least two symbols.
- The code of a symbol is the sequence of bits on the path from the root.
- If a shortest code is required, discard this tree and run Huffman on the same probabilities.
Prefix-free does not mean optimal. Huffman is the optimal prefix code for a given set of symbol probabilities. Arithmetic coding can do better still by using fractional bits. Shannon-Fano is the top-down split, kept for history and for comparison.
Approaches that look simpler and fail
| Approach | Why it fails when the top-down split is described as optimal |
|---|---|
| Claim every balanced split yields a minimum average length | Some probability lists have a Shannon-Fano code longer than their Huffman code. The split is a heuristic tree, not the Huffman merge. |
| Split by count of symbols instead of probability | A cut that equalizes the number of symbols can put all the probability on one side. The weights are what matter. |
| Omit the sort | The two-group picture assumes the list is ordered so a single cut is a contiguous segment. An unsorted list needs a different partition search. |
| Use the code as a compressor without a model | The tree encodes symbols at the probabilities it was given. A mismatched model expands the file. |
The optimal prefix code is Huffman. Fractional bits are arithmetic coding. Shannon-Fano is the top-down probability split.
A working example
This Python fragment splits the symbols into two groups of nearly equal weight and recurses. The weights 35, 17, 17, 16, 15 produce a prefix code whose weighted length is 233. A Huffman code for the same weights has weighted length 230. It prints 233.
weights = [("a", 35), ("b", 17), ("c", 17), ("d", 16), ("e", 15)]
def split(group):
if len(group) == 1:
return {group[0][0]: ""}
total = sum(w for _, w in group)
acc = 0
cut = 1
for i, (_, w) in enumerate(group[:-1], 1):
acc += w
cut = i
if acc >= total / 2:
break
left = split(group[:cut])
right = split(group[cut:])
codes = {k: "0" + v for k, v in left.items()}
codes.update({k: "1" + v for k, v in right.items()})
return codes
codes = split(weights)
total = sum(dict(weights)[name] * len(code) for name, code in codes.items())
assert total == 233
print(total)
Where it is used
Shannon-Fano is the split used by the old ZIP implode method. DEFLATE, which replaced it, uses Huffman coding. The two build a prefix code; Huffman merges the lightest trees and Shannon-Fano splits the weight in half.
When you can drop this algorithm
Drop Shannon-Fano when you are choosing a prefix code for a real compressor. Build a Huffman tree. Keep the split as a comparison that shows why the bottom-up merge is the optimal rule.
Why this stays published
We publish this so a search for Shannon-Fano returns the top-down split and the fact that Huffman can beat it on the same weights. Shannon-Fano builds a prefix code by recursively splitting symbols into two groups of nearly equal probability, and that code is not always as short as a Huffman code.
本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。
