Computer ScienceAlgorithmsMedium

Topological Sort

Also known as:Topological OrderingTopo SortDAG Linearization

Topological Sort is a linear ordering of vertices in a Directed Acyclic Graph (DAG) such that for every directed edge (u → v), vertex u appears before vertex v in the ordering. It is only possible for DAGs — graphs with cycles cannot be topologically sorted. Topological sort is essential in task scheduling, build systems (e.g., Makefile dependency resolution), course prerequisite ordering, and instruction scheduling in compilers.

Topological Sort Algorithms Comparison

AlgorithmApproachTime ComplexitySpace ComplexityCycle Detection
Kahn's AlgorithmBFS-based, in-degree countingO(V + E)O(V)Yes — detects if sort incomplete
DFS-based SortDFS post-order reversalO(V + E)O(V)Yes — via back-edge detection
Both produceValid linear order of DAGO(V + E)O(V)Equivalent in correctness
Applicable toDAGs onlyLinear in graph sizeVertex storageNot valid for cyclic graphs

Interactive Tools

VisuAlgo – Topological Sort

Interactive visualization of DFS-based topological sorting on DAGs

Open Tool

Brilliant.org – Topological Sort

Problem-based learning for topological ordering in graphs

Open Tool

Khan Academy – Graph Algorithms

Introduction to topological ordering with DAG examples

Open Tool
Directed Acyclic Graph (DAG) illustrating a topological ordering of nodes

Wikimedia Commons, CC BY-SA

Related Terms

From Greek topos (place) and logos (study), giving "topology" — the mathematical study of properties preserved under continuous deformations. "Topological sort" was adopted in computer science in the 1960s to describe ordering vertices by their dependency structure. The algorithm was formalized in works by Arthur Kahn (1962) and others.

daggraphorderingschedulingalgorithmscomputer-science