Take the 2-minute tour ×  I have a set of data on which I need
to perform a topological sort, with a few assumptions and
constraints, and I was wondering if anyone knew an existing,
efficient algorithm that would be appropriate for this.    • The
data relationships are known to form a DAG (so no cycles to
worry about).   • An edge from A to B indicates that A depends
on B, so B must appear before A in the topological ordering.   •
The graph is not necessarily connected; that is, for any two
nodes N and M there may be no way to get from N to M by
following edges (even if you ignore edge direction).   • The
data relationships are singly linked. This means that when there
is an edge directed from A to B, only the A node contains
information about the existence of the edge.  The problem can be
formulated as follows:  Given a set of nodes S in graph G which
may or may not have incoming edges, find a topological ordering
of the subgraph G' consisting of all of the nodes in G that are
reachable from any node in set