Topological Sort Algorithms For A Directed Acyclic Graph




First Version of Topological Sort of a Directed Acyclic Graph

Procedure TopologicalSort
{
  Let N = the number of vertices;
  Let L be an empty list ;
  For step 1 to N
  {
     Let V be a vertex in the graph that has no successors ;
     Insert V into the first position of list L;
     Delete V and its incident edges from the graph;
  }
}

When the algorithm terminates L contains the vertices of the
original graph in a topological order.


Second Version of Topological Sort of a Directed Acyclic Graph Procedure TopologicalSort { Initialize status = WAITING for all vertices; Let L be an empty list ; Let S be an empty stack; For each vertex V in the graph If (V has no predecessors) { Set status(V) = VISITED ; Push V onto S; } While (S is not empty) { Let X be the top element of S; If (X has an adjacent vertex N with status(N) = WAITING) { Set status(N) = VISITED ; Push N onto S; } Else { Pop X ; Insert X into the first position of list L; } } /* end while */ } When the algorithm terminates L contains the vertices of the original graph in a topological order.