| |||||||||
In combinatorics, topologically sorting a directed acyclic graph (DAG) means finding a linear ordering of the nodes so that any node x in the linear order comes before any other node y, if there's a path through the DAG leading from x to y.
The usual algorithm for topological sorting has running time linear in the number of nodes plus the number of edges. It works by depth first search. First, find a list of "start nodes" which have no incoming edges. Put them into a queue Q. Then,
If this algorithm terminates without outputting all the nodes from the graph, it means the graph has at least one cycle and is not a DAG, so the algorithm can report an error.