| • Science | • People | • Locations | • Timeline |
The canonical application of topological sorting is in scheduling a sequence of jobs. The jobs are represented by vertices, and there is an edge from x to y if job x must be completed before job y can be done. Then, a topological sort gives an order in which to perform the jobs. This has applications in computer science, such as in instruction scheduling, ordering of formula cell evaluation in Microsoft Excel and makefiles.
The graph shown to the left has many valid topological sorts, including:
|
The usual algorithm for topological sorting has running time linear in the number of nodes plus the number of edges ( Θ(|V|+|E|)). It uses depth-first search. First, find a list of "start nodes" which have no incoming edges and insert them into a queue Q. Then,
while Q is nonempty remove a node n from Q output n for each node m with an edge e from n to m remove edge e from the graph if m has no other incoming edges insert m into QIf this algorithm terminates without outputting all the nodes of the graph, it means the graph has at least one cycle and therefore is not a DAG, so the algorithm can report an error.