Skip to content
Part IA Lent Term

Topological Sort

Definition

A topological ordering of a directed graph is a linear ordering of its vertices such that for every directed edge uvu \to v, vertex uu appears before vertex vv in the ordering. A topological ordering exists iff the graph is a DAG (no directed cycles). If cycles exist, no such ordering is possible: a cycle abcaa \to b \to c \to a would require aa before bb before cc before aa, a contradiction.

DFS-Based Algorithm

Run a full DFS on the graph. As each vertex finishes (colour changes from grey to black), prepend it to a list. The final list is a topological order.

Pseudocode:

TOPOLOGICAL-SORT(G):
  for each v in G.V:
    v.colour = WHITE
  L = empty list         // will hold result
  for each v in G.V:
    if v.colour == WHITE:
      DFS-VISIT-TOPO(G, v)
  return L

DFS-VISIT-TOPO(G, u):
  u.colour = GREY
  for each v in G.Adj[u]:
    if v.colour == GREY: report "cycle exists"
    if v.colour == WHITE:
      DFS-VISIT-TOPO(G, v)
  u.colour = BLACK
  prepend u to L

Running time: Θ(V+E)\Theta(|V| + |E|) with adjacency lists.

Why Reverse Finish Time?

For any edge uvu \to v in a DAG, DFS produces f[v]<f[u]f[v] < f[u]. Proof: when (u,v)(u,v) is explored, vv cannot be grey (that would be a back edge → cycle, impossible in DAG). If vv is white, vv becomes a descendant of uu, so f[v]<f[u]f[v] < f[u] by the parenthesis theorem. If vv is black, then f[v]<d[u]<f[u]f[v] < d[u] < f[u], so again f[v]<f[u]f[v] < f[u]. In all cases vv finishes before uu. Sorting by decreasing f[v]f[v] therefore places uu (later finish) before vv (earlier finish), satisfying uvu \to v.

Source-Removal Algorithm (Alternative)

An alternative approach repeatedly removes sources (vertices with in-degree 0):

TOPOLOGICAL-SORT-SOURCES(G):
  compute in-degree[v] for all v
  Q = queue of all vertices with in-degree 0
  L = []
  while Q not empty:
    u = DEQUEUE(Q)
    append u to L
    for each v in G.Adj[u]:
      in-degree[v] = in-degree[v] - 1
      if in-degree[v] == 0:
        ENQUEUE(Q, v)
  if |L| != |V|: graph has a cycle
  return L

Also Θ(V+E)\Theta(|V| + |E|). This version is sometimes called Kahn’s algorithm and has the advantage of detecting cycles explicitly (if L<V|L| < |V|, a cycle exists).

Worked Example

DAG with vertices {A,B,C,D,E}\{A,B,C,D,E\} and edges: ABA \to B, ACA \to C, BDB \to D, CDC \to D, DED \to E.

DFS method: Run DFS starting from AA:

  • Visit AA (d=1), then BB (d=2), then DD (d=3), then EE (d=4). EE finishes (f=5), DD finishes (f=6), BB finishes (f=7). Back to AA, visit CC (d=8), CC finishes (f=9). AA finishes (f=10).
  • Finish times (decreasing): A(10), C(9), B(7), D(6), E(5).
  • Topological order: A,C,B,D,EA, C, B, D, E.

Source-removal method:

  • Initial in-degrees: A=0, B=1, C=1, D=2, E=1.
  • Pick A (indeg 0). Remove A: decrease B→0, C→0. Queue: [B, C]. Output: [A].
  • Pick B. Remove B: decrease D→1. Queue: [C]. Output: [A,B].
  • Pick C. Remove C: decrease D→0. Queue: [D]. Output: [A,B,C].
  • Pick D. Remove D: decrease E→0. Queue: [E]. Output: [A,B,C,D].
  • Pick E. Remove E. Output: [A,B,C,D,E].

Both methods produce valid topological orders (note: A, C, B differs from A, B, C — both are valid since B and C are incomparable).

Applications

  • Task scheduling: tasks with prerequisites; topological order gives a valid execution sequence.
  • Build systems: make uses topological sort to determine which targets to build first.
  • Course prerequisite planning: courses with dependencies form a DAG.
  • SSSP on DAGs: relaxing edges in topological order solves SSSP in Θ(V+E)\Theta(|V|+|E|), even with negative edge weights (but no cycles).

Summary

PropertyDetail
Exists iffGraph is a DAG
DFS methodOutput in decreasing f[v]f[v] order
Source removalRepeatedly remove in-degree-0 vertices
Time (both)Θ(V+E)\Theta(V+E)
DAG SSSPRelax edges in topological order, Θ(V+E)\Theta(V+E)

Past paper questions: y2026p1q10 (topological sort algorithm, DAG transitive closure).