Why does JPEG read its 64 DCT coefficients in zig-zag order? See how the scan creates long runs of zeros that RLE and Huffman coding squeeze into a few bits.
Before JPEG hands the 64 quantized coefficients of an 8×8 DCT block to entropy coding, it has to flatten the 2D array into a 1D sequence. It does not simply read row by row (row-major). It reads in zig-zag order.
As you learned in Chapter 3, DCT coefficients have their energy concentrated at low frequencies and fall toward 0 as frequency rises. Reading in zig-zag order puts the large coefficients first and the near-zero ones last, which creates long runs of zeros. Compress those runs with RLE (Run-Length Encoding) and 'twelve zeros in a row' can be expressed in just a few bits.
JPEG groups the coefficients into (run, value) pairs, meaning 'this many zeros, then this value', and Huffman-codes those pairs. If all the remaining coefficients are zero, a single EOB (End Of Block) symbol covers the rest of the block.
At higher quality (lower QP) there are more nonzero coefficients, so the EOB comes later. At lower quality the EOB comes sooner and the file gets smaller.
The combination of zig-zag scan + RLE + entropy coding survives almost unchanged in CAVLC in H.264. The coefficient coding based on CABAC in HEVC and adaptive arithmetic coding in AV1 is more sophisticated (for example, it adapts the diagonal scan direction to the block content), but the underlying principle is the same: 'put large coefficients first and zeros last to maximize the runs'.
The order that unfolds 2D DCT coefficients into 1D from low frequency to high frequency.
A technique that compresses runs of the same value (especially 0) into a count.
End Of Block. A special symbol signaling that all remaining coefficients are zero.
Context-Adaptive Variable-Length Coding. H.264's method of coding the runs of zeros produced by RLE with Huffman-family codes chosen according to context.
Lossless entropy coding that assigns a whole number of bits to each symbol according to its probability.
Why does zig-zag scanning help compression?