charlesreid1.com blog

Generating Functions Part 1: Solving the Quicksort Recurrence

Posted in Mathematics

permalink

This post is part 1 of a series on generating functions, based on notes we have been working through from Sedgewick and Flajolet's Analysis of Algorithms and Trotter's Applied Combinatorics. The full set of notes lives on our wiki: Generating Functions.

Generating functions are one of those techniques that look completely mysterious the first time you see them, and then look like the obvious thing to do the tenth time you see them. They turn recurrences into functions, functions into series, and series back into closed forms for the coefficients you actually wanted. This post walks through one of the nicest applications: solving the recurrence relation for quicksort.

The Recurrence

The average number of comparisons quicksort makes on an array of size \(n\) satisfies the recurrence

$$ C_n = n + 1 + \dfrac{2}{n} \sum_{1 \leq k \leq n} C_{k-1} $$

The \(n+1\) term is the cost of the partition step. The sum averages the cost of recursing on the two subarrays over all possible choices of pivot.

Staring at that sum inside the recurrence is not a great starting point. Everything on the right depends on every \(C_k\) that came before. Generating functions are how we get out.

Setting Up the Generating Function

The plan is to introduce a generating function

$$ C(z) = \sum_{n \geq 0} C_n z^n $$

and then translate each piece of the recurrence into an operation on \(C(z)\).

Multiplying the recurrence by \(n\) to clear the \(\tfrac{2}{n}\), and then by \(z^n\), and summing over \(n\), we end up with

$$ \sum_{n \geq 1} n C_n z^n = \sum_{n \geq 1} n(n+1) z^n + 2 \sum_{n \geq 1} \sum_{1 \leq k \leq n} C_{k-1} z^n $$

Each of these three terms turns into something in \(C(z)\):

  • The left side is \(z C'(z)\), since taking a derivative and multiplying by \(z\) pulls out an \(n\) from each term of the series
  • The first term on the right involves the second derivative of \(\tfrac{1}{1-z}\), and simplifies to \(\tfrac{2}{(1-z)^3}\)
  • The double sum is a partial-sum operation, which corresponds to multiplying by \(\tfrac{1}{1-z}\)

Putting it all together, we get

$$ C'(z) = \dfrac{2}{(1-z)^3} + \dfrac{2 C(z)}{1 - z} $$

The recurrence has become a first-order linear differential equation.

Solving the ODE

To solve

$$ C'(z) - \dfrac{2 C(z)}{1 - z} = \dfrac{2}{(1-z)^3} $$

we look for an integrating factor \(\rho(z)\) such that \(\rho'(z) = -\dfrac{2 \rho(z)}{1-z}\). That works out to \(\rho(z) = (1-z)^2\).

Multiplying through:

$$ \left( (1-z)^2 C(z) \right)' = \dfrac{2}{1-z} $$

Integrating both sides:

$$ (1-z)^2 C(z) = 2 \ln \left( \dfrac{1}{1-z} \right) $$

And so

$$ C(z) = \dfrac{2}{(1-z)^2} \ln \left( \dfrac{1}{1-z} \right) $$

That is the generating function for the average number of comparisons in quicksort. Not obvious.

Reading Off the Coefficient

Now we extract \(C_n = [z^n] C(z)\). The expression \(\tfrac{1}{(1-z)^2}\) has the well-known expansion \(\sum (n+1) z^n\), and \(\ln \left( \tfrac{1}{1-z} \right)\) has the expansion \(\sum \tfrac{z^k}{k}\), which is the generating function for the sequence \(H_k = 1 + \tfrac{1}{2} + \dots + \tfrac{1}{k}\) (the harmonic numbers, once you divide by \(\tfrac{1}{1-z}\) to accumulate).

Working through the convolution, we land at

$$ C_n = 2(n+1)(H_{n+1} - 1) $$

That is the closed form. Since \(H_n \approx \ln n + \gamma\) for large \(n\), this gives \(C_n \sim 2 n \ln n\), which recovers the familiar \(O(n \log n)\) average case for quicksort - with an actual constant in front of it.

Why This Is Worth Learning

The reason this technique is so satisfying is that we started with a recurrence that looked completely intractable - \(C_n\) depends on the entire prefix \(C_0, C_1, \dots, C_{n-1}\) - and ended with a clean closed form.

The mechanical steps are:

  1. Turn the recurrence into a functional equation in \(C(z)\) by multiplying by \(z^n\) and summing.
  2. Solve the functional equation. Sometimes it is algebraic, sometimes it is a differential equation (as here).
  3. Extract the \(n\)-th coefficient of the solution.

In upcoming posts in this series, we will look at simpler examples that show how the coefficient extraction step works, including a nice puzzle about distributing colored marbles into cans with weird constraints.

References

Tags:    mathematics    generating functions    algorithms    quicksort    recurrence    sedgewick   

A Pair of Dice Games (or, Why Chevalier de Méré Lost Money)

Posted in Mathematics

permalink

Here is a nice little problem from Paul Nahin's Will You Be Alive 10 Years From Now?. It is a problem from the 1654 correspondence between Antoine Gombaud (the Chevalier de Méré) and Blaise Pascal - one of the founding episodes of probability theory, dressed up as a gambling puzzle.

(This one lives on our wiki as FMM21, part of our Friday Morning Math Problem series.)

The Two Games

Game 1. You toss a single die \(N_1\) times. What should \(N_1\) be to make the probability of seeing at least one 6 greater than \(\tfrac{1}{2}\)?

Game 2. You toss a pair of dice \(N_2\) times. What should \(N_2\) be to make the probability of seeing at least one double 6 greater than \(\tfrac{1}{2}\)?

In gambling terms, the question is: what is the smallest \(N\) that turns an even-money bet on "at least one 6" (or "at least one double 6") into a bet that favors the gambler rather than the house?

Game 1

Pascal's trick is to count the complement. There are \(6^{N_1}\) ways for the die to land over \(N_1\) tosses, and \(5^{N_1}\) of them have no 6 at all. So

$$ P_1 = 1 - \left(\dfrac{5}{6}\right)^{N_1} $$

We want \(P_1 > \tfrac{1}{2}\), which is easiest to just tabulate:

  • \(N_1 = 1\): \(P_1 = 0.167\)
  • \(N_1 = 2\): \(P_1 = 0.306\)
  • \(N_1 = 3\): \(P_1 = 0.421\)
  • \(N_1 = 4\): \(P_1 = 0.518\)

So \(N_1 = 4\).

Game 2

Same trick with a pair of dice. The probability of a double 6 on a single toss is \(\tfrac{1}{36}\), so the probability of not rolling a double 6 is \(\tfrac{35}{36}\), and

$$ P_2 = 1 - \left(\dfrac{35}{36}\right)^{N_2} $$

Tabulating:

  • \(N_2 = 24\): \(P_2 = 0.491\)
  • \(N_2 = 25\): \(P_2 = 0.506\)

So \(N_2 = 25\).

Gombaud's Mistake

Here is the fun part.

Gombaud believed in strict proportionality. He reasoned that since Game 1 had 6 outcomes per toss and Game 2 had 36 outcomes per toss, the answers should be related by

$$ \dfrac{N_1}{6} = \dfrac{N_2}{36} $$

With \(N_1 = 4\), that gives \(N_2 = 24\). And Gombaud, who was a very careful gambler, actually played this game for money on the belief that \(N_2 = 24\) was the tipping point.

But it turns out that \(N_2 = 24\) gives a probability of \(0.491\), which is just barely on the wrong side of \(\tfrac{1}{2}\). Gombaud noticed, over a large number of games, that he was consistently losing money at \(N_2 = 24\). Being unable to figure out why, he wrote to Pascal.

The intuition that ratios of counts should scale linearly is one of those things that feels obviously true and is very quietly false. The correct answer is off by one - \(N_2 = 25\), not \(24\) - and that one integer of difference was enough to drain the Chevalier's purse.

The Moral

There are two morals, depending on your temperament:

  • If you are a probability theorist, the moral is: complementary events are your friend, and multiplying \(\tfrac{5}{6}\) by itself is a lot easier than enumerating all the ways to see at least one 6.

  • If you are a gambler, the moral is: do not let intuition about ratios substitute for actual arithmetic, and if a French nobleman offers you an even-money bet on rolling a double 6 in 24 throws, take it.

More

Tags:    mathematics    probability    dice    pascal    friday morning math   

Installing LaTeX Packages on macOS: The `~/Library/texmf` Layout

Posted in LaTeX

permalink

Every few years, we find ourselves installing a new LaTeX package on a Mac, and every few years, we find ourselves searching for the same set of directory paths, the same texhash invocation, and the same reminders that the LaTeX package installer is not, in fact, going to create any directories for us.

So this post is here mostly as a note to our future selves.

Where TeX Looks First

We use MacTeX (http://www.tug.org/mactex/), and MacTeX installs its files under /usr/local/texlive/. That is the system-wide texmf tree.

Personal TeX files should not go there. They should go under ~/Library/texmf, which is your user-level texmf tree. When TeX needs to find a file, it looks in ~/Library/texmf/ first, and the system-wide texmf second. So if you drop a modified version of a system file into your user tree, the modified version wins.

The Directory Layout

The folder structure inside ~/Library/texmf should mirror the structure of the system texmf tree. Here is where different kinds of files go:

  • TeX files: ~/Library/texmf/tex (or any subfolder of it)
  • LaTeX files: ~/Library/texmf/tex/latex
  • LyX files: ~/Library/texmf/tex/latex/lyx
  • BibTeX .bib files: ~/Library/texmf/bibtex/bib
  • BibTeX .bst (bib style) files: ~/Library/texmf/bibtex/bst

If any of these directories don't exist, you have to create them. Most TeX or LaTeX installers will not create them for you. Just run

mkdir -p ~/Library/texmf/tex/latex

and you are on your way.

Rehashing After You Add Files

When you drop a new file or folder into the texmf tree, TeX will not find it until you rehash the TeX database. The command is:

texhash ~/Library/texmf

If you don't know where your texmf directories are in the first place, running texhash on its own will update the database and print the paths it found, which is a nice way to discover the layout on any given machine.

Example: The cancel Package

The cancel package is a small package for drawing slashing arrows through terms in equations (nice for "goes to zero" or "goes to infinity" annotations in engineering equations).

Installing it on a Mac is one of the easier cases:

  • Download the package zip
  • Unzip it
  • Drop the .sty file into ~/Library/texmf/tex/latex
  • Run texhash ~/Library/texmf

That's it - no sudo, no system-wide install, no touching /usr/local.

What About Windows?

Use MikTeX: http://miktex.org/. MikTeX has its own package manager and handles most of this automatically. Consider yourself lucky.

When Things Go Wrong: Conflicts With Fink

One historical footgun that we hit years ago, and mention here in case someone else runs into it: if you have Fink installed, Fink may install its own copy of pdftex, and Fink may be putting /sw (or whatever your Fink prefix is) at the front of your $PATH.

If that happens, pdftex from the command line resolves to the Fink version, not the MacTeX version, and things get confusing quickly.

Two fixes:

  1. Stop sourcing /sw/bin/init.sh (or pathsetup.sh) from your dotfiles, and add /sw to your $PATH manually so MacTeX wins.

  2. Call pdftex with the full path when you mean the MacTeX version: /usr/texbin/pdftex ...

Both are annoying. Option 1 is less annoying long-term.

More notes on our LaTeX page: https://charlesreid1.com/wiki/LaTeX

Tags:    latex    mac    tex    texmf    packages   

November 2026

Baby Mac Crypto

March 2022

How to Read Ulysses

July 2020

Applied Gitflow

September 2019

Mocking AWS in Unit Tests

November 2017

A Hard(y) Math Problem