Chapter 4. The Stable Marriage Problem
The Gale-Shapley algorithm in its imperative form.
This page: Classical forms. View LLP forms »
GaleShapley
The classical man-optimal algorithm: each iteration picks any free man and lets him
propose to his next preference. G[i] records the number of proposals man i
has made so far.
Time complexity: $O(n^2)$, where $n$ is the number of men (= number of women).
int[] match(int[][] mpref, int[][] rank) {
int n = mpref.length - 1;
int[] G = new int[n + 1];
int[] partner = new int[n + 1];
boolean[] free = new boolean[n + 1];
forall i in [1..n] : free[i] = true;
boolean done = false;
while (!done) {
int i = 1;
while (i <= n && !free[i]) { i = i + 1; };
if (i > n) {
done = true;
} else {
G[i] = G[i] + 1;
int z = mpref[i][G[i]];
if (partner[z] == 0) {
partner[z] = i;
free[i] = false;
} else {
if (rank[z][i] < rank[z][partner[z]]) {
free[partner[z]] = true;
partner[z] = i;
free[i] = false;
}
}
}
};
return G;
}
Looking ahead
The lattice-linear reformulation that this classical algorithm implicitly walks through is on the LLP companion page: it makes explicit that Gale-Shapley is a fixed-point iteration on the proposal-vector lattice.