Topological Sort — Definition & Example
Topological sort is a way of listing the vertices of a directed graph so that every arrow points from an earlier vertex to a later one. It works like scheduling tasks so that each prerequisite comes before the tasks that depend on it.
Let be a directed graph with . A topological ordering of is a bijection assigning the vertices positions such that for every directed edge , you have . A topological ordering exists if and only if is a directed acyclic graph (DAG). Kahn's algorithm and depth-first search each compute one in time.
How It Works
Kahn's algorithm is the most common method. First, compute the in-degree of every vertex, which is the number of edges pointing into it. Next, repeatedly remove a vertex with in-degree 0, append it to the output, and subtract 1 from the in-degree of each vertex it points to. If you remove all vertices, the output is a topological order. If vertices remain but none has in-degree 0, the graph contains a directed cycle. Depth-first search also works: run DFS, record each vertex when it finishes, and list the vertices in reverse finishing order.
Worked Example
Problem: A build has tasks A to E with these dependencies: A → C, B → C, C → D, B → E, and E → D. Use depth-first search finishing times to produce a valid build order.
Step 1: Start a depth-first search at A. Go from A to C, then from C to D. D has no outgoing edges, so D finishes first. Then C finishes, then A.
Step 2: A is done but B is not visited, so start again at B. B points to C, which is already finished, and to E. E points only to D, which is finished, so E finishes, then B.
Step 3: Reverse the finishing order to get a topological order. Check each edge: A is before C, B is before C, C is before D, B is before E, and E is before D.
Answer: One valid order is B, E, A, C, D. The order A, B, C, E, D is also valid, because A has no path to or from B or E, and C has none to or from E.
Why It Matters
Build tools such as Make, spreadsheet recalculation engines, and package managers like npm use topological sort to decide what to compute or install first. In an algorithms course, it is the standard first step for finding shortest and longest paths in a DAG in linear time.
Common Mistakes
Mistake: Assuming a DAG has only one topological order.
Correction: Most DAGs have several valid orders. Whenever two vertices have in-degree 0 at the same time, either one can come next. The order is unique only when the DAG contains a directed path that visits every vertex.
