The Sweep-Cut Algorithm
The proof of the hard side of Cheeger's inequality is really an algorithm: sort the vertices by an eigenvector and return the best prefix. This lesson implements it in time after the vector is known, and makes one observation that matters in practice: the proof never needs an exact eigenvector. Any degree-balanced vector with a small Rayleigh quotient gives a good cut, so a few hundred iterations of the power method are enough.
The algorithm
sweep_cut(G, x) x: one real value per vertex
1 order ← vertices sorted by x O(n log n)
2 inS ← all false; cut ← 0; vol ← 0; best ← ∞
3 for i ← 1 to n − 1 (prefix S_i = first i vertices)
4 v ← order[i]; inS[v] ← true; vol ← vol + d(v)
5 for each neighbour u of v
6 if inS[u] then cut ← cut − w(u, v) (edge now inside S)
7 else cut ← cut + w(u, v) (edge now leaves S)
8 φ ← cut / min(vol, vol(V) − vol)
9 if φ < best then best ← φ; bestIndex ← i
10 return the first bestIndex vertices of order, bestEach edge is touched twice over the whole sweep (once from each endpoint), so lines 3 to 9 cost ; the sort dominates with . Computing is the expensive part.
Which vector? For the guarantee , sweep over where is an eigenvector of the normalized Laplacian for ; equivalently solves the generalized problem . Sweeping over the eigenvector of the unnormalized also works well in practice and has an analogous guarantee for in terms of and .
Approximate vectors suffice. Read the proof again: steps 1 to 3 use only that and that the Rayleigh quotient is small. So:
Theorem (sweep for any vector). For every with , the best sweep set of has conductance at most .
This is what makes spectral partitioning practical: run power iteration (or Lanczos) until , and sweep.
An implementation
The program plants three groups of 12 vertices with denser edges inside, computes two ways (exactly with eigh, and approximately with 30 steps of deflated power iteration on , whose top eigenvalues correspond to the bottom of ), and checks the sweep guarantee for each.
import random
import numpy as np
def sweep_cut(adj, deg, x):
"""Best prefix of the vertices sorted by x: returns (conductance, set)."""
order = sorted(range(len(x)), key=lambda v: (x[v], v))
total = sum(deg)
in_s = [False] * len(x)
cut = vol = 0.0
best, best_i = float("inf"), 0
for i, v in enumerate(order[:-1], start=1):
in_s[v] = True
vol += deg[v]
for u in adj[v]:
cut += -1 if in_s[u] else 1
phi = cut / min(vol, total - vol)
if phi < best:
best, best_i = phi, i
return best, sorted(order[:best_i])
rng = random.Random(11)
n, k = 36, 12
edges = [(u, v) for u in range(n) for v in range(u + 1, n)
if rng.random() < (0.5 if u // k == v // k else 0.04)]
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v); adj[v].append(u)
deg = np.array([len(a) for a in adj], dtype=float)
A = np.zeros((n, n))
for u, v in edges:
A[u, v] = A[v, u] = 1
L = np.diag(deg) - A
s = 1 / np.sqrt(deg)
M = s[:, None] * A * s[None, :] # D^(-1/2) A D^(-1/2) = I - N
vals, vecs = np.linalg.eigh(np.eye(n) - M)
nu2 = float(vals[1])
def rayleigh(x):
return float(x @ L @ x / (x @ (deg * x)))
top = np.sqrt(deg) / np.linalg.norm(np.sqrt(deg)) # eigenvector of nu_1 = 0, to deflate
y = np.random.default_rng(3).standard_normal(n)
for _ in range(30):
y = y + M @ y # (I + M) has eigenvalues 2 - nu_i >= 0
y -= (y @ top) * top
y /= np.linalg.norm(y)
print(f"{len(edges)} edges, nu_2 = {nu2:.4f}, nu_3 = {float(vals[2]):.4f}, nu_4 = {float(vals[3]):.4f}")
print(f"Cheeger bound sqrt(2 nu_2) = {np.sqrt(2 * nu2):.4f}")
for name, x in [("exact eigenvector", vecs[:, 1] * s), ("30 power steps", y * s)]:
R = rayleigh(x)
phi, S = sweep_cut(adj, deg, x)
print(f"{name:18}: R(x) = {R:.4f}, sweep conductance {phi:.4f} <= sqrt(2 R) = {np.sqrt(2 * R):.4f}")
print(f"{'':18} set found: {S}")107 edges, nu_2 = 0.1484, nu_3 = 0.2058, nu_4 = 0.4947
Cheeger bound sqrt(2 nu_2) = 0.5448
exact eigenvector : R(x) = 0.1484, sweep conductance 0.1343 <= sqrt(2 R) = 0.5448
set found: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]
30 power steps : R(x) = 0.1659, sweep conductance 0.1600 <= sqrt(2 R) = 0.5759
set found: [1, 2, 3, 5, 6, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
The exact eigenvector separates one planted group, vertices 12 to 23, from the other two (the set printed is the complement), with conductance 0.13, far below the Cheeger bound: the bound is pessimistic for graphs with clear clusters. The 30-step vector is worse. With three groups, and are close (the spectrum has a cluster of three small eigenvalues, one per group, as the lesson on spectral clustering explains), so power iteration mixes the two eigenvectors for a long time and the sweep set straddles the groups. Still, its conductance respects its own guarantee , as the theorem promises for every vector.
In C++
The same sweep with adjacency lists and an incremental cut, together with the power iteration that produces the vector, on a grid in which the middle column's horizontal edges have been removed except one. The optimal cut is obvious to a human; the algorithm finds it from the spectrum.
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <numeric>
#include <vector>
using Graph = std::vector<std::vector<int>>;
// Fiedler-like vector by power iteration on (I + D^-1/2 A D^-1/2), deflating sqrt(d).
std::vector<double> spectral_vector(const Graph& g, int steps) {
int n = (int)g.size();
std::vector<double> sd(n), y(n), z(n);
double norm_top = 0;
for (int v = 0; v < n; ++v) { sd[v] = std::sqrt((double)g[v].size()); norm_top += sd[v] * sd[v]; }
for (int v = 0; v < n; ++v) y[v] = std::sin(1.0 + 7.0 * v); // a fixed, irregular start vector
for (int t = 0; t < steps; ++t) {
for (int v = 0; v < n; ++v) {
double s = 0;
for (int u : g[v]) s += y[u] / sd[u];
z[v] = y[v] + s / sd[v];
}
double dot = 0, nrm = 0;
for (int v = 0; v < n; ++v) dot += z[v] * sd[v];
for (int v = 0; v < n; ++v) { z[v] -= dot / norm_top * sd[v]; nrm += z[v] * z[v]; }
for (int v = 0; v < n; ++v) y[v] = z[v] / std::sqrt(nrm);
}
for (int v = 0; v < n; ++v) y[v] /= sd[v]; // x = D^-1/2 y
return y;
}
// Best prefix of the vertices sorted by x; returns its conductance and fills `best_set`.
double sweep(const Graph& g, const std::vector<double>& x, std::vector<int>& best_set) {
int n = (int)g.size();
std::vector<int> order(n);
std::iota(order.begin(), order.end(), 0);
std::stable_sort(order.begin(), order.end(), [&](int a, int b) { return x[a] < x[b]; });
long total = 0;
for (auto& nb : g) total += (long)nb.size();
std::vector<char> in(n, 0);
long cut = 0, vol = 0;
double best = 1e9;
int best_i = 0;
for (int i = 0; i + 1 < n; ++i) {
int v = order[i];
in[v] = 1;
vol += (long)g[v].size();
for (int u : g[v]) cut += in[u] ? -1 : 1;
double phi = double(cut) / double(std::min(vol, total - vol));
if (phi < best) { best = phi; best_i = i + 1; }
}
best_set.assign(order.begin(), order.begin() + best_i);
std::sort(best_set.begin(), best_set.end());
return best;
}
int main() {
const int R = 3, C = 12, n = R * C;
Graph g(n);
auto add = [&](int a, int b) { g[a].push_back(b); g[b].push_back(a); };
for (int i = 0; i < R; ++i)
for (int j = 0; j < C; ++j) {
int v = i * C + j;
if (i + 1 < R) add(v, v + C);
if (j + 1 < C && (j != 5 || i == 1)) add(v, v + 1); // only row 1 crosses the middle
}
for (int steps : {20, 200, 2000}) {
std::vector<int> S;
double phi = sweep(g, spectral_vector(g, steps), S);
std::printf("%4d power steps: sweep conductance %.4f, |S| = %zu\n", steps, phi, S.size());
if (steps == 2000) {
for (int i = 0; i < R; ++i) {
for (int j = 0; j < C; ++j)
std::printf("%c", std::binary_search(S.begin(), S.end(), i * C + j) ? 'S' : '.');
std::printf("\n");
}
}
}
} 20 power steps: sweep conductance 0.0182, |S| = 18
200 power steps: sweep conductance 0.0182, |S| = 18
2000 power steps: sweep conductance 0.0182, |S| = 18
......SSSSSS
......SSSSSS
......SSSSSS
The sweep separates the two halves through the single remaining edge, conductance (each half has volume 55), already after 20 steps: here is far below , so power iteration converges quickly.
Common mistakes
- Sweeping the wrong vector. The guarantee is for , not for the eigenvector of itself. On regular graphs the two differ only by a constant factor and it does not matter; on graphs with hubs it does.
- Splitting at zero or at the median. Taking the signs of , or forcing equal halves, is one particular sweep set. The theorem is about the best of all prefixes; a fixed split can be far worse (see the cockroach graph in Higher-Order Cheeger).
- Recomputing the cut from scratch for every prefix. That costs ; the incremental update in lines 5 to 7 is what makes the sweep linear.
- Trusting a repeated eigenvalue's vector. If , the solver may return any vector of the eigenspace and the sweep result depends on it; sweep a few vectors of the eigenspace, or all of the bottom eigenvectors, and keep the best set.
Local versions
The sweep needs a global vector, so it costs at least linear time. For huge graphs one often wants a small cluster around a given seed vertex in time proportional to the cluster, not the graph. Spielman and Teng (2004) gave the first such local clustering algorithm (Nibble: truncated random walks from the seed, followed by sweeps), and Andersen, Chung and Lang (2006) replaced the walk by an approximate personalized PageRank vector computed by a push procedure, with a sweep over . Given a seed in a target set of conductance , Nibble finds a set of conductance about , and Andersen, Chung and Lang improved this to ; both run in time nearly linear in the volume of the output (times a factor polynomial in ). These local algorithms are subroutines of the nearly-linear-time Laplacian solver of Spielman and Teng (Nearly-Linear-Time Laplacian Solvers).
Test yourself
After sorting, how long does the sweep over all prefixes take?
- , because each edge's contribution to the cut changes only when one of its endpoints moves into
Which property of the vector does the sweep guarantee need?
- must be an exact eigenvector
- Only ; the bound is in terms of its own Rayleigh quotient
- must be nonnegative
- must have distinct entries
To guarantee , which vector should be swept?
- The eigenvector of for itself
- , i.e. a solution of
- The degree vector
- The eigenvector of the largest eigenvalue of
What do local clustering algorithms such as Andersen-Chung-Lang (PageRank-Nibble) achieve?
- Exact minimum conductance
- A low-conductance set near a seed in time nearly linear in the size of the output, not the graph
- Optimal bisections
- Exact eigenvectors in linear time