TopologicalSort
Topological ordering of directed acyclic graphs (DAGs).
A topological sort produces a linear ordering of vertices such that for
every directed edge u → v, vertex u appears before v in the
ordering. This is only possible when the graph has no directed cycles.
Both implementations return nil when a cycle is detected, signaling that
no valid topological order exists.
When to use each variant
| Function | Strategy | Best when |
|---|---|---|
sort |
DFS post-order | General purpose |
kahn |
BFS / in-degree queue | You also need the in-degree counts, or want a more predictable iteration order |
All functions accept either callback form for GetNeighbors — see
GraphUtil for details.
Example graph
-- Task dependency graph (directed, acyclic):
-- compile ──→ link ──→ test ──→ deploy
-- ↑
-- assets ─────┘
local deps = {
compile = {},
assets = {},
link = {"compile", "assets"},
test = {"link"},
deploy = {"test"},
}
local allTasks = {"compile", "assets", "link", "test", "deploy"}
local function getNeighbors(v)
return deps[v] -- outgoing edges (v must come before its neighbors)
end
Functions
sort
directed
Returns a topological ordering of allVertices using iterative
DFS post-order. Each vertex is appended once all its outgoing edges are
explored, yielding reverse-topological order; the list is flipped once at the
end so dependencies land before dependents.
Returns nil if the graph contains a directed cycle (no valid ordering
exists).
local order = TopologicalSort.sort(allTasks, getNeighbors)
-- e.g. { "compile", "assets", "link", "test", "deploy" }
Time complexity: O(V + E)
kahn
directedReturns a topological ordering using Kahn's algorithm (BFS / in-degree queue). Vertices with zero in-degree are enqueued first; as each is removed, the in-degrees of its successors are decremented and any newly zero-degree successors are enqueued.
Returns nil if the graph contains a directed cycle (not all vertices
could be processed).
local order = TopologicalSort.kahn(allTasks, getNeighbors)
-- e.g. { "compile", "assets", "link", "test", "deploy" }
Stable ordering
Kahn's approach processes vertices in FIFO order within the same in-degree level, which can produce a more predictable ordering than DFS for graphs with multiple valid topological sorts.
Time complexity: O(V + E)